149x Filetype PDF File size 0.22 MB Source: dec.vumk.eu
CS 16 Introduction to Algorithms and Data Structures Introduction to Python - 2019 Introduction to Python - 2019 Due: February 14th, 11:59pm Overview Welcome to the Python lab! The lab is in two parts. Both parts are due on February 14th at 11:59, but we strongly recommend you complete Part 1 before working on Homework 2, and complete Part 2 before working on Homework 3. PART1 1 What is Python? Asnake! A snake! A scaaary snake? Yes, but Python is also a programming language that you’ll be learning this semester! Python bears some resemblance to Java, but in general it is cleaner and easier to read. There are a few important differences from Java that you should note: First, you don’t need to declare the types of variables. Thus, you write x = 1 rather than int x = 1. Variables do have types, but you don’t need to announce the type when you first use a variable. In fact, you can write x = 1 and then x = "abcd" in the same program; after the first assignment, x is an integer; after the second, it’s a string. (N.B. In general this is a very bad idea, so avoid it!) Second, the environment in which you work with Python lets you type bits of code and see what happens without an intermediate compiling step. This makes experimentation and testing very simple. Third, a feature of Python that you will grow to love and cherish is how easy it is to read. Instead of using a lot of punctuation and other symbols, which are what makes code in most programming languages look daunting and scary, Python uses English keywords and natural-sounding syntax. For example, this is a declaration and an if-condition in Python: x = 1 if x > 0: print "x is positive" print "What beautiful syntax!" print "Do you love Python yet?" You’ll notice that instead of using curly braces to delimit code blocks, Python uses whites- pace indentation. That means that correctly nesting your code now has semantic meaning, instead of just making it easier for you (and your TAs) to read. We’ll learn more about syntax later, so for now, just marvel at its beauty. Introduction to Python - 2019 January 31, 2019 1 CS 16 Introduction to Algorithms and Data Structures Introduction to Python - 2019 Python is similar to Java in that it also handles your memory management, meaning it allocates memory and has a garbage collectorf to free up that memory once it is no longer needed, making your life a whole lot easier. If you’re not already convinced that Python rules... 2 Whyshould you learn Python? We’ll be using Python throughout the semester to code up some of the algorithms you’ll be learning. As a computer scientist you should get used to learning new languages readily, not only because it’s an important part of the subject, but also because it’s useful (and fun!). Python is especially important to learn because it is used very widely as a scripting language – Pixar uses it for all their tools, for instance – so knowing it could one day help you get a job making a movie like Toy Story 3. 3 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!” 3.1 Setting up Run cs0160 install pythonIntro from the command line. This will install a folder pythonIntro in your cs0160 directory. It should contain two files primePrinter.py and sectionOne.py. 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 Atom. If you are working from a computer in the Sunlab or MSlab, complete Section 3.2, which will tell you how to configure Atom universally for Python code, and skip over Section 3.3. If you have Atom locally on your personal computer, you can follow the same instructions to configure it, although some of the instructions may be a little different depending on how you work locally. If you are working remotely, jump right to section 3.3 to learn how to set up Gedit, which performs better over SSH. Either way, be sure to begin again at Section 3.4, where you will write your first Python program! 3.2 Working from the Sunlab or MSlab Open the text editor Atom, by typing atom & in your terminal. First we will make the .py file you will write your program in. 1. Create a new file: File > New File Introduction to Python - 2019 January 31, 2019 2 CS 16 Introduction to Algorithms and Data Structures Introduction to Python - 2019 2. Save this file, File > Save, naming it helloWorld.py. The .py is very important!! Make sure the file is saved in your ~/course/cs0160/pythonIntro directory. Wenowneed to configure Atom to work best with Python: 1. From the menu bar, select Edit > Preferences. This should open up a new tab in the editor. Scroll down to the Editor Settings section. This is where you can configure different preferences for your Atom. Take a look at some of the options and feel free to play around with them. 2. Change the Tab Length to be 4 and make sure the Tab Type is set to soft. 3. Close this tab and you’re ready to go! 3.3 Working romotely over SSH Gedit performs much better over SSH, so you should use this program to work on the lab if you are not on a CS department computer. Type gedit & into a terminal and press Enter to open Gedit. First we will make the .py file you will write your program in. 1. Save the current (blank) new file: File > Save as... 2. NamethefilehelloWorld.py. The .py is very important!! Make sure the file is saved in your ~/course/cs0160/pythonIntro directory. Next, we have to configure Gedit to work well with Python. 1. Go to Edit->Preferences 2. Click on the Editor tab 3. Ensure that Tab width is set to 4 4. Check the box that says Insert spaces instead of tabs Close out of the preferences window. You’re all set! 3.4 Let’s get to coding! From 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 - 2019 January 31, 2019 3 CS 16 Introduction to Algorithms and Data Structures Introduction to Python - 2019 print ‘Hello world!’ and save your file. Now go back to your terminal, make sure you are in the pythonIntro directory and type python helloWorld.py to run the program. It will print Hello world! to your terminal. Hold on, do you really have to type python yourProgramName.py every time you want to run a program? (Or for the especially lazy, scroll through your commands until you find the last time you typed it?) Heck no! Go back to your editor and type: #! /usr/bin/python at the top of your helloWorld.py file. This tells your machine to use Python to interpret the file when executed. Then save the file, go back to your terminal, and type chmod +x helloWorld.py to make the file an executable. (If you haven’t used chmod before, it’s a terminal command used to change file permissions, in this case to make your Python file executable. The +x argument adds executability for the owner of the file, you!) Now if you type ./helloWorld.py into your terminal your program prints Hello world! to the terminal. From now on, all of your Python files should start with #! /usr/bin/python. 4 Python Syntax Let’s say that instead of wanting to write a program that just prints “Hello world!” and then ends, you wanted to write a program with a function that takes in a string with your name as the parameter, and prints “Hello!” Following the CS16 Python coding conventions, the function would look like this: def say_hello(name): """say_hello: string -> nothing Purpose: prints a greeting of the form "Hello !" Example: say_hello("Seny") -> "Hello Seny!" """ print "Hello " + name + "!" #this is the function body Whenyoudefineafunction in Python, you simply write def (which is 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. Note that you do not need to specify the type of your parameters in Python! Next, document your function with a block comment! Use triple quotes (""" to create block comments much like /* would in Java. For an in-line comment, use #, instead of the // from Java. This 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 and 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. Introduction to Python - 2019 January 31, 2019 4
no reviews yet
Please Login to review.