Rules for variable names
Names cannot start with a number
Names cannot contain spaces (use underscore symbol instead)
Names cannot contain any of these symbols:
:'",<>/?|\!@#%^&*~-+
Names usually are best represented using only lowercase with underscore (more information can be found here)
Avoid using Python built-in keywords such as list and str
Avoid using the single characters l ( lowercase of letter L), O (uppercase of letter o) and I (uppercase of letter i) since they often can be confused with number 1 and 0.
Just like how int is a data type referring to whole numbers, str is another data type referring to plain text. This functions similar to the Panel in Grasshopper.
String Indexing and Slicing
We know strings are a sequence, which means Python can use indexes to call parts of the sequence. Indexing - Retrieving one letter from the string Slicing - Retrieving multiple letters (Sub-string) from the string
In Python, we use brackets [] after an object to call its index. We should also note that indexing starts at 0 for Python. Let's create a new object called s and then walk through a few examples of indexing.
Syntax for []: Starting Index (Inclusive), End Index (Exclusive), Step Size
my_var = "Hello World"
# Outputs the first letter. Remember: In Python, index starts from '0'
print(my_var[0])
# Outputs the first to fourth letter. Indexing works by INCLUDING left bound but EXCLUDING right bound
print(my_var[0:4])
# Outputs the first and third letter.
print(my_var[0:4:2])
# Reversing a string
print(my_var[::-1])
From top to bottom, this will output:
H
Hell
Hl
dlroW olleH
String Properties
It's important to note that strings have an important property known as immutability. This means that once a string is created, the elements within it can not be changed or replaced. For example:
s = "Hello World"
s[0] = 'x'
This will output:
TypeError: 'str' object does not support item assignment
Notice how the error tells us directly what we can't do, change the item assignment!
Something we can do is concatenate strings!
String Concatenation
Dictionary definition of concatenation: "the action of linking things together in a series, or the condition of being linked in such a way"
Layman term: Joining 2 or more strings together
s = "Hello World"
# Concatenate strings!
s + ' concatenate me!'
# We can reassign s completely though!
s = s + ' concatenate me!'
print(s)
This will output:
Hello World concatenate me!
We can use the multiplication symbol to create repetition as well.
letter='z'
letter*10
This will output:
zzzzzzzzzz
Earlier when discussing strings we introduced the concept of a sequence in Python. Lists can be thought of the most general version of a sequence in Python. Unlike strings, they are mutable, meaning the elements inside a list can be changed!
Lists are constructed with brackets [] and commas separating every element in the list.
# Assign a list to a variable named my_list
my_list = [1,2,3]
# For Python, different data types can be put together into the same list
my_list = [1, "2", True]
Indexing and Slicing
Indexing and slicing work similar like in strings.
Nesting Lists
A great feature of Python data structures is that they support nesting. This means we can have data structures within data structures. For example: A list inside a list.
Let's see how this works!
# Let's make three lists
lst_1=[1,2,3]
lst_2=[4,5,6]
lst_3=[7,8,9]
# Make a list of lists to form a matrix
matrix = [lst_1,lst_2,lst_3]
print(matrix)
This will output
[[1,2,3],[4,5,6],[7,8,9]]
Built-in Functions / Methods
Python comes with built-in functions / methods that can be applied to a few data types or which are unique only to a specific data type.
len() is a built-in function which returns the length of the string / object.
An object is an instance of a class.
A class, in a nutshell, is a bundle of functions. However, when functions are placed inside classes, they are known (Read: Defined) as methods.
print(len("Letters")) # Outputs number of letters
print(len([1,2,3,5,8])) # Outputs number of elements
Built-in Methods for Lists
Few examples include:
pop() Removes the last element from the list.
append() Adds an element to the back of the list.
reverse() Reverses the order of all elements in the list.
Note: All 3 of these functions are applied directly to the original list
# Remove the last element from the list
ls = [1,2,3,4,5,"This will be removed from the list"]
print(ls)
ls.pop() # Note that .pop() is applied directly to the list I.e. There is no need to do ls = ls.pop()
print(ls)
# Add an element to the back of the list
ls.append(6)
print(ls)
# Reverses the order of the list
ls.reverse()
print(ls)
This will output:
[1,2,3,4,5,"This will be removed from the list"]
[1,2,3,4,5]
[1,2,3,4,5,6]
[6,5,4,3,2,1]
We've been learning about sequences in Python but now we're going to switch gears and learn about mappings in Python. If you're familiar with other languages you can think of these Dictionaries as hash tables.
So what are mappings? Mappings are a collection of objects that are stored by a key, unlike a sequence that stores objects by their relative position. This is an important distinction, since mappings won't retain order since they have objects defined by a key.
A Python dictionary consists of a key and then an associated value. That value can be almost any Python object.
Constructing a Dictionary
Let's see how we can construct dictionaries to get a better understanding of how they work!
# Make a dictionary with {} and : to signify a key and a value
my_dict = {'key1':'value1','key2':'value2'}
# Access a value by inputting its key
my_dict["key1"]
# Dictionaries, like lists, can hold different data types
my_dict = {'key1':123,'key2':[12,23,33],'key3':['item0','item1','item2']}
# The values can be reassigned
my_dict["key1"] = 456
# New values can be assigned
my_dict["key4"] = "New Value"
print(my_dict)
# Accessing nested dictionaries
d = {'k1': [1,2,{'k2':[["Hello!"]]}]}
print(d['k1'][2]['k2'][0][0])
This will output:
{'key1': 456, 'key2': [12, 23, 33], 'key3': ['item0', 'item1', 'item2'], 'key4': 'New Value'}
Hello!
In Python tuples are very similar to lists, however, unlike lists they are immutable meaning they can not be changed. You would use tuples to present things that shouldn't be changed, such as days of the week, or dates on a calendar.
You'll have an intuition of how to use tuples based on what you've learned about lists. We can treat them very similarly with the major distinction being that tuples are immutable.
Constructing Tuples
The construction of a tuples use () with elements separated by commas. For example:
tup = ("This will not change", True)
print(tup)
This will output:
("This will not change", True)
Immutability
It can't be stressed enough that tuples are immutable. No variable reassignment!
To drive that point home:
tup = ("This will not change", True)
tup[0] = "This will not work"
print(tup[0])
This will output:
TypeError: 'tuple' object does not support item assignment
Sets are an unordered collection of unique elements. We can construct them by using the set() function.
What's the purpose? One main reason is to identify unique elements from a list
x = set()
x.add(1)
print(x)
This will output:
{1}
Note the curly brackets. This does not indicate a dictionary! Although you can draw analogies as a set being a dictionary with only keys.
We know that a set has only unique entries. So what happens when we try to add something that is already in a set?
x.add(1)
print(x) # Notice how there is still only 1 element?
This will output:
{1}
if Statements in Python allows us to tell the computer to perform alternative actions based on a certain set of results. The logic behind this is that it will check whether the if condition is fulfilled, if not it will check the next elif. Then, if all of the if and elif conditions are not fulfilled, it will execute the command under else.
my_list = [1,2,3,4,5]
# If the first element of the list is equal to 5, print "Yes"
if my_list[0] == 5:
print("Yes")
# If the first element of the list is equalt to 4, print "No"
elif my_list[0] == 4:
print("No")
# If both conditions above are not fulfilled, print "Maybe"
else:
print("Maybe")
This will output:
Maybe
+ is an addition operator. It adds two values.
- is a subtraction operator. It subtracts one value from another.
* is a multiplication operator. It multiplies values on either side of the operator.
/ is a division operator. It divides the left operand by the right operand.
% is a modulus operator. It gives the remainder of division.
** is an exponent operator. It calculates exponential power value. a**b gives the value of a to the power of b.
// is an integer division which is also called floor division. It performs division and gives only an integer quotient.
a=5
b=2
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a%b)
print(a**b)
print(a//b)
This will output:
7
3
10
2.5
1
25
2
A for loop acts as an iterator in Python; it goes through items that are in a sequence or any other iterable item. Objects that we've learned about that we can iterate over include strings, lists, tuples, and even built-in iterables for dictionaries, such as keys or values.
Here's the general format for a for loop in Python:
for item in object:
statements to do stuff
Note that the two lines above are not Python code but simply the logic behind the for loop in Python.
# Iterating through a list
list1 = [1,2,3,4,5,6,7,8,9,10]
# Note: The list can also be created via range()
list2 = list(range(1,11))
for x in list1:
print(x)
# This is the same as the following:
for x in range(1,11):
print(x)
This will output:
1
2
3
4
5
6
7
8
9
10
Another example of for loop is to create Fibonacci Sequence:
# Number of steps
n = 10
# Define first and second element of Fibonacci sequence to be '1' and '1'
if n == 0:
l = [1]
elif n == 1:
l = [1,1]
else:
l = [1,1]
n1 = 1
n2 = 1
# Code out the Fibonacci Sequence
for i in range(2,n+1):
n3 = n1 + n2
n1 = n2
n2 = n3
l.append(n3)
print(l)
This will output:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Formally, a function is a useful device that groups together a set of statements so they can be run more than once. They can also let us specify parameters that can serve as inputs to the functions. It allows code to be reused over and over again without us rewriting everything.
For example:
def main():
print('abc')
main()
main()
This will output:
abc
abc