Introduction to Python#

Variables#

Variables are named values.

a = 4

Read this as:

“a” gets the value 4.

b = 6

“b” gets the value 6.

a + b
10

You can also update variables, as in:

a = a + 2
a
6

So far we’ve seen numbers as values, but we can also have bits of text called strings. Strings are bits of text between quotes.

a = "Python"
c = "MATLAB"
z = " > "

You have seen adding numbers. We can also add strings. This as the effect of sticking them together — concatenating the strings:

a + z + c
'Python > MATLAB'

Strings can have apostrophes (') or inverted commas (") at either end, Python accepts either.

first = 'a string'
second = "b string"
first + second
'a stringb string'

You can even use triple apostrophes or inverted commas at either end; this is useful for when you want to put a new line inside your string:

many_line_string = """
This string
has
several
lines
"""
print(many_line_string)
This string
has
several
lines

Length of a string:

len(first)
8

Strings and numbers are different:

number = "9"
number + 6
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[10], line 2
      1 number = "9"
----> 2 number + 6

TypeError: can only concatenate str (not "int") to str

We can convert between numbers and strings:

int(number) + 6
str(9)
'9'

However …

number = "nine"
int(number)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[12], line 2
      1 number = "nine"
----> 2 int(number)

ValueError: invalid literal for int() with base 10: 'nine'

Lists#

an_empty_list = []
list_with_two_items = [1, 2]
items_can_be_diverse = [1, "Obama", 4.55]
example_list = []
example_list.append("experiment1")
example_list
['experiment1']
example_list[0]
'experiment1'

The length of a list (or any object that can have a length):

len(example_list)
1
example_list.append("failed_experiment")
print(example_list)
example_list.append("failed_experiment")
print(example_list)
['experiment1', 'failed_experiment']
['experiment1', 'failed_experiment', 'failed_experiment']
example_list.pop()
'failed_experiment'
example_list
['experiment1', 'failed_experiment']
del example_list[0]
example_list
['failed_experiment']

range in returns a “range object”. It’s like a list, but isn’t quite a list.

range(10)
range(0, 10)

You can make it into a list by using the list constructor. A constructor is like a function, but it creates a new object, in this case a new object of type list.

list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

You can also set the start element for range:

list(range(2, 7))
[2, 3, 4, 5, 6]

Use in to ask if a element is a collection of things, such as a range, or a list:

5 in range(2, 7)
5 in [2, 5, 7]
True
9 in range(2, 7)
False

Sets#

Sets are unordered, and unique.

“Unordered” means the order is arbitrary, and Python reserves the right to return the elements in any order it likes:

our_work = set(["metacognition", "mindwandering", "perception"])
print(our_work)
{'perception', 'mindwandering', 'metacognition'}

If you want to get a version of the set that is ordered, use sorted, which returns a sorted list:

sorted(our_work)
['metacognition', 'mindwandering', 'perception']

You can’t index a set, because the indices 0, or 1, or 2 don’t correspond to any particular element (because the set is unordered):

our_work[0]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[28], line 1
----> 1 our_work[0]

TypeError: 'set' object is not subscriptable

Add to a set with the add method:

our_work.add("consciousness")
print(our_work)
{'perception', 'mindwandering', 'consciousness', 'metacognition'}
our_work.add("consciousness")
print(our_work)
our_work.add("consciousness")
print(our_work)
{'perception', 'mindwandering', 'consciousness', 'metacognition'}
{'perception', 'mindwandering', 'consciousness', 'metacognition'}

You can subtract sets:

competing_labs_work = set(["motor control", "decision making", "memory", "consciousness"])
what_we_should_focus_on = our_work - competing_labs_work
print(what_we_should_focus_on)  
{'perception', 'mindwandering', 'metacognition'}
what_we_should_avoid = our_work.intersection(competing_labs_work)
print(what_we_should_avoid)
{'consciousness'}

Sets have lengths as well:

len(what_we_should_focus_on)
3

Working with strings#

We have already seen strings. Here is another example.

example = "mary had a little lamb"
print(example)
mary had a little lamb

String slicing:

example[0]
'm'
example[0:4]
'mary'

You can split strings with any character. This breaks up the string, returning a list of strings broken at the separator character:

example.split(" ")
['mary', 'had', 'a', 'little', 'lamb']
example.split(" ")[4]
'lamb'

You can split with any character:

another_example = 'one:two:three'
another_example.split(":")
['one', 'two', 'three']

You can also strip a string. That returns a new string with spaces, tabs and end of line characters removed from the beginning and end:

my_string = ' a string\n'
my_string
my_string.strip()
'a string'

Adding strings:

example + " or two"
'mary had a little lamb or two'

Putting strings into other strings:

subject_id = "sub1"
print(f"Subject {subject_id} is excellent")
Subject sub1 is excellent
age = 29
print(f"Subject {subject_id} is {age} years old")
Subject sub1 is 29 years old

You can do more complex formatting of numbers and strings using formatting options after a : in the placeholder for the string. See: https://docs.python.org/3.5/library/string.html#format-examples.

print("Subject {:02d} is here".format(4))
Subject 04 is here

For loop#

for i in range(10):
    print(i)
0
1
2
3
4
5
6
7
8
9

Indentation is crucial!

for i in range(10):
print(i)
  Cell In[46], line 2
    print(i)
    ^
IndentationError: expected an indented block after 'for' statement on line 1

Watch out for mistakes:

for i in range(10):
    j = i + 1
print(j)
10

Ifs and breaks#

a = 2
b = 5
c = a + b
if c < 6:
    print("yes")
if c < 6:
    print("yes")
else:
    print("no")
no
if c < 6:
    print("yes")
elif c > 6:
    print("no")
else:
    print("kind of")
no
if True:
    print("true, true!")
true, true!
if False:
    print("never!")
for i in range(10):
    if i == 6:
        break
    print(i)
0
1
2
3
4
5
for i in range(10):
    if i == 6:
        continue
    print(i)
0
1
2
3
4
5
7
8
9

Logic#

You can use logical operators like and, or and not:

strange_election = True
uncomfortable_choices = True
satisfying_experience = False
strange_election and uncomfortable_choices
strange_election and satisfying_experience
strange_election and not satisfying_experience
True

We often use these in if statements:

if strange_election and not satisfying_experience:
    print('Watching a lot of news')
Watching a lot of news

Files#

Use pathlib to write text and read text from files.

Write lines to a text file:

from pathlib import Path

path = Path("important_notes.txt")
type(path)
pathlib.PosixPath
my_text = """captains log 672828: I had a banana for breakfast.
captains log 672829: I should watch less TV.
"""

print(my_text)
captains log 672828: I had a banana for breakfast.
captains log 672829: I should watch less TV.
path.write_text(my_text)
96

Read lines from a text file:

text_again = path.read_text()
print(text_again)
captains log 672828: I had a banana for breakfast.
captains log 672829: I should watch less TV.

Split the lines from a text into a list, where there is one element per line, and each element is a string:

# The splitlines method of a string.
lines = text_again.splitlines()

len(lines)
print(lines[0])
print(lines[1])
captains log 672828: I had a banana for breakfast.
captains log 672829: I should watch less TV.

We may want to delete the file when we’ve finished with it. Again the Path object does the job:

# Delete the file.
path.unlink()