Recitation: How to Learn Python


Using Python

For this course, we’ll always be using Python 3. There are a few options for how to edit and run Python code. Typically you will edit your code in a text editor and run it through a terminal. Options for text editors on the CS department machines include

When opening existing files in these programs, be careful, as they may change tabs to spaces.

There are a few options for IDEs for Python. One of the most popular is PyCharm, but it is unfortunately not available on the CS department machines.

To run a Python script using a terminal, navigate to the folder containing the script using

cd <folder location>

then

python3 <filename>.py

Depending on the installation, it may just be python rather than python3.

If you want to install Python on your own machine, https://www.python.org/downloads/ has the downloads. You will likely need to add Python to your path. There is usually an option to do this during install, but otherwise you may have to search how to set it up on your home computer. Alternatively, you can transfer the files to a CS machine using SCP and use SSH to run it from there.

Basic Syntax

A hello world program in Python is just

print('Hello World')    

A slightly more complex program is (your TA will talk you through what it does):

import sys

def name_of_function(var1, var2):
    # This is a comment!
    sum = 0
    for i in range(var1):
        sum += var2
    return sum
    
if __name__ == '__main__':
    num_to_do = int(sys.argv[1])
    num_to_add = int(sys.argv[2])
    result = name_of_function(num_to_do, num_to_add)
    print(result)

How to Teach Yourself Python

Use some of these resources to learn about Python lists and slices. Are Python lists passed by value or by reference? What do you expect the following code snippets to do and why?

Snippet one

a_list = ['this is a list', 3, ['this is a sublist']]

print(len(a_list))

a_list.append(True)
print(a_list)
print(len(a_list))

a_list = a_list + [3.0, 4.0, 5.0]
print(a_list)
print(len(a_list))

Snippet two

integers = list(range(-10, 10, 2))
print(integers[2:5])
print(integers[-5:-1])
print(integers[::2])

Snippet three

def doubler(a_list):
    for elem in a_list:
        elem = 2*elem

def doubler2(a_list):
    for i in range(len(a_list)):
        a_list[i] = 2*a_list[i]
        
first_list = ['a', 1, [0, 1]]
doubler(first_list)
print(first_list)

second_list = ['a', 1, [0, 1]]
doubler2(second_list)
print(second_list)

Recursion

Most of the programming assignments in this course will be easier to solve using recursion. Here’s an example of a basic recursive program:

def fibonacci(n):
    if n <= 1:
        return 1
    return fibonacci(n-1) + fibonacci(n-2)
    
print(fibonacci(10))