









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










Introduction to Python
Welcome to the Python lab! This is due one week after you start the lab in section, to be handed in by the next section (this means each person’s due date depends on when they have section).
Python is a programming language! It bears some resemblance to Java, but in general it is cleaner and easier to read. A few more important differences from Java:
x = 1 if x > 0: print("x is positive") print("What beautiful syntax!") print("Do you love Python yet?")
Like Java, Python also handles your memory management, meaning it allocates memory and has a garbage collector to free up that memory once it is no longer needed. This makes your life a lot easier!
Introduction to Python
2 Writing your first program in Python
It’s tradition when learning a new programming language that your first program is a “Hello World” program, so let’s start out by writing a simple one-line program that prints “Hello World!”
Clone the Python Lab stencil code from GitHub into a directory of your choosing on your computer. Click here to get the stencil code. Check out the Github Guide for more details about how to clone a repo! If you have a Windows computer, make sure you’re using Git Bash (which comes with your installation of Git) or some other Linux terminal to run the commands described. Before we begin programming, we need to configure the editor you will use to write your Python code. While you are free to use any editor of your choice, we recommend you use VSCode.
First we will make the .py file you will write your program in.
If you took CS15, you are probably familiar with using these text editors to write Java (.java) code. We’ll be using them to write Python (.py) files in CS16. It’s important you have configured your editor as specified above because Python uses whitespace indentation to delimit your code (more on this later). For the sake of conve- nience, we insist that you use 4 spaces to indent your code. It will make your code look consistent across machines and prevent inconsistencies between spaces and hard tabs. Now, let’s begin! Type:
Introduction to Python
When you define a function in Python, you simply write def (short for define), followed by the name of the function, with all words lowercase and separated by underscores, then the parameters in parentheses, and lastly a colon. You do not need to specify the type of your parameters in Python! Next, document your function with a block comment! Triple quotes (""") create block comments much like /* do in Java. # creates an in-line comment, like // in Java. The block comment should include a description of the parameters and return type, the purpose of the method, and an example of the method in use. This type of block comment is called a docstring. It is crucial to writing readable code that is easy to understand later. There is a detailed handout on coding conventions on the course website that you can read for more information on writing good Python. The actual body of this function is simple:
To test out this function, type it into your text editor, and put this code at the end:
if name == "main": say_hello("Doug") # substitute your name
It’s very important this code comes after the function definition, because unlike Java, Python functions must be defined before they can be called. This bit of code will allow you to run it as a standalone program. The main line here is similar to Java’s public static void main(String args[]). It contains the code that will run when you execute the program. Save your file (make sure it ends in .py) and then run it using one of the two techniques we discussed earlier. The terminal will now greet you as if your name is Doug; substitute your name into the parameters and it will greet you!
gemini ~/course/cs0160 $ python3 sayHi.py Hello Doug!
Let’s look at something a little more complicated. Say you wrote out pseudocode for a function that prints out the numbers 1 to n for n ≥ 1. It might look something like this:
Algorithm printOneToN(n): This algorithm prints out the numbers from 1 to n for n ≥ 1. If n is less than 1, it prints an error message to alert the user. Input: an integer n
Introduction to Python
Output: none
if n < 1 then print "Invalid input: integer value cannot be less than 1" return for i from 1 to n print i
In Python, following the CS16 Python coding conventions, it would look like this:
def print_one_to_n(n): """print_one_to_n: int -> nothing Purpose: this function prints out the numbers from 1 to n for n >= 1. If n is less than 1, it prints an error message to alert the user. """ if n < 1: print("Invalid input: integer value cannot be less than 1") return for i in range(1, n + 1): print(i)
Notice that there aren’t many differences between the pseudocode and Python. That’s one of the reasons Python is so wonderful! Let’s go over some of the new Python syntax.
if not n > 0:
There is a lot more to Python syntax, but these are some basics to get you started. Here is a super nifty Java to Python conversion table, which will be a boon to you in the coming weeks (note that some of these, like print, were still written in Python2):
Introduction to Python
won’t waste time looking for bugs in the wrong place. Let’s take a look at assert.
def add(a, b): return a + b
if name == "main": assert add(2, 3) == 5, "Arithmetic failure"
assert will check that both sides of the equality are equal. If the evaluation of the first ar- gument does not equal the second argument, an AssertionError exception will be thrown, printing the (optional) message. More generally, if the statement following assert evaluates to False, then the exception will be thrown and print out the (optional) message. We will be putting a lot of emphasis on testing throughout this course, in homeworks and projects. Testing should not be considered an additional aspect of a problem or project, but rather a core part of it. Given this, we want you to write your tests before you write your code. This practice is known as Test-Driven Development (TDD for short). We’ll be walking you through the steps of TDD that will help you write code for is prime. To test factorial (more on this method in the next section), print the result of the factorial method with a number you pass in. If your code returns the correct value, you’ve probably implemented it correctly.
def factorial(n): """factorial: int [n] → int [n!] Purpose: Returns the factorial of the argument Example: factorial(4) -> 24 """
Introduction to Python
When you reach the Python problem in sectionOne.py, you’ll see that there is some code at the beginning of the function body of factorial that looks like this:
if n < 0: raise InvalidInputException("input must be greater than or equal to 0")
This is called raising (or throwing) an exception. You may be familiar with some excep- tions (e.g. the dreaded NullPointerException or ArrayIndexOutOfBoundsException) from your work in CS15 last semester. Exceptions are used to detect various errors during program execution. Now, you will learn how to raise your own exceptions! Woohoo!!
Open sectionOne.py and examine the code above. When computing the factorial of a number, that number must be an integer greater than or equal to 0. But what if the user of your program doesn’t know that, and they try to run factorial(-3)? The above if statement will be entered, and an InvalidInputException will be raised. If this if state- ment was not present in the code, there would be some pretty big issues, as your base case would never be reached, and the method would infinitely recur.
When you write methods, your job is to ensure that the input given is valid before contin- uing on with your program. Using if statements with similar structure to the one above, you have to check for valid input - if the input is invalid, you have to raise an InvalidInpu- tException that prints out an informative message regarding why the exception was raised. Don’t worry about writing your own InvalidInputException class, and, for now, don’t worry about determining whether a number is an integer or decimal.
5 Your First Python Problem
Now it is time to write a short Python program that prints out the first 100 Fibonacci numbers. Remember, each number in the Fibonacci series is the sum of the two numbers before it, and the first and second numbers of the series are both one. Once you complete this assignment, create a second method which recursively calculates and returns n! where n is the input value. Make sure to follow the testing design recipe for this problem.
Introduction to Python
“But what if I need a multi-dimensional list/array?” you ask. Great question! Python handles this data structure as a list of lists:
>>> grid = [[1,2,3], [4,5,6], [7,8,9]] >>> grid [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> grid[0][1] 2 >>> grid[2] [7,8,9] #notice that row 2 is itself a list within the 2D grid list
This may seem strange at first, but as long as you remember “lists within lists,” you’ll be fine. You can read about additional Python data structures, (like dictionaries!) at: https://docs.python.org/3.7/tutorial/datastructures.html
Python supports a concept called “list comprehensions” which can help you create lists very easily. Here are a few examples:
>>> vec = [2, 4, 6] >>> [3x for x in vec] [6, 12, 18] >>> [[x,x2] for x in vec if x > 3] #x2 in Python is xx [[4, 16], [6, 36]] >>> [[0]*3 for i in range(3)] [[0,0,0],[0,0,0],[0,0,0]]
7 Object-oriented programming in Python
Python supports object-oriented programming as you learned in CS15 with Java. To do so, you declare a class with properties (instance variables) and capabilities (methods) as follows:
class Student: """The student class models a student with a name, ID number, a graduation year, and a concentration. """
def init(self, name, idNumber, concentration, graduationYear): self._name = name self._idNumber = idNumber self._graduationYear = graduationYear
Introduction to Python
self._concentration = concentration
def set_concentration(self, concentration): self._concentration = concentration
def print_student_info(self): print("Student named " + self._name + " has ID number " + str(self._idNumber) + ", is graduating in " + str(self._graduationYear) + " and is studying " + self._concentration + ".")
To see how this Python class may be compared to a Java implementation, check out the file Student.java.To actually create an instance of this class, and call methods on it, we do the following:
if name == "main" : dara = Student("Dara", 1002354, "Physics", 2018) dara.set_concentration("Computer Science") dara.print_student_info()
Create a file called student.py and test this out for yourself. What does this example show us?
Introduction to Python
8 File I/O
File I/O is very simple in Python, and is one of the tools we’ll expect you to become familiar with this semester. You can manipulate files from JPEGS to spreadsheets, but we’ll start off working with a simple text file. Open up the demo.txt file, to see what you’ll be working with. Now, open up Python in your terminal by running python3, and try out the following commands:
>>> myfile = open("demo.txt") >>> colors = [] >>> for line in myfile: ... colors.append(line) #be sure to tab on this line ... >>> myfile.close() >>> print(colors) [’red\n’, ’orange\n’, ’yellow\n’, ’green\n’, ’blue\n’, ’indigo\n’, ’violet\n’] >>> for hue in colors: ... print(hue.strip()) ... red orange yellow green blue indigo violet
The \n character is called a “newline” and represents a carriage return in a file. We use the strip() method to remove unneeded whitespace from our strings. Always make sure to close the files you open to avoid eating up system resources.
Try the following code in the Python interactive interpreter:
>>> file = open(’my_file.txt’, ’w’) #the ’w’ arg allows us to write to the file >>> file.write(’This is the first line\n’) >>> for i in range(11): ... file.write(str(i) + ’\n’) ... >>> file.close()
Introduction to Python
Verify that this code created a file named my file.txt in your current directory that contains “This is the first line” and the numbers 0-10. The built-in function str() converts objects, such as ints, to their string representations.
9 Writing your second program in Python!
Yay! Now it’s time to play with objects in Python! Also with pies! Because pies are amaz- ing and delicious. In your pythonIntro folder, you should see two files called pieCount.txt and pieCounter.py. pieCount.txt is a text file (woohoo! you know how to read from and write to these) with each line of the form , . Through- out the month, TAs have been recording how many pies they eat and is the number of pies that a given TA ate at a given sitting.
The file pieCounter.py in your stencil folder is an almost empty .py file that you’ll fill up with code! YAY!
You should create one object that takes in a filename (a Python string) as a parameter to its constructor. You can call your object whatever you want, but I’ll refer to it as PieCounter. PieCounter should have one method (which I’ll call count pies) that takes in the name of a specific TA, counts up how many pies that the TA has eaten this month, and prints that number. Once you’ve written your class, instantiate your class in the name == " main " block at the bottom of the .py file and call your method, passing in a few different TA names. Some examples are Lisa Yang, Doug Woos, and Lucy Qu.
As usual, we expect you to use asserts to test your functions. Refer to the Student class for help on the syntax to call class methods. Write method signatures for methods you might need for the class you are about to write and follow the testing design recipe from day 1 to write test cases. Read the hints section that follows for ideas on how to factor code into test-able methods. Do not yet worry about testing for invalid file names given to the open() method. You will learn how to test exceptions on a future homework. We do expect that you will test the functionality of the string parsing you do on the contents of the file.
Introduction to Python
def function():
if name == "main":
All your Python handins are required to follow this convention. We will deduct points from your grade if your code does not include this, so don’t forget!
We require you to follow the CS16 coding conventions for Python assignments throughout the semester. We expect you to read and follow it. You can find the coding conventions here: CS16 Python Convention
This introduction to Python only scratches the surface of what Python is and what it can do. You can find the official tutorial here: https://docs.python.org/3/tutorial/. The sections that will be most useful for CS16 are: 1, 3, 4.1-4.6, 4.7.6, 5, 6, 7.1, 8.1-8.5 and 9.3. Take a look at this blog post about common anti-patterns and how to avoid them. Anti-patterns are, essentially, coding solutions many people use that are inefficient, con- fusing, or even incorrect. Following some of the tips in this post can make your Python programs more efficient and more readable.