Pythonintroin Your Cs0160Directory. It Should Contain Two

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 36

pythonIntroin your cs0160directory.

It should contain two


lesprimePrinter.pyand
sectionOne.py.
Before we begin programming, we need to con
gure 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 4.2, which will tell you how to con
gure Atom universally for Python code, and
skip over Section 4.3. If you have Atom locally on your personal computer, you can
follow
the same instructions to con
gure it, although some of the instructions may be a little
di#erent depending on how you work locally. If you are working remotely, jump right
to
section 4.3 to learn how to set up Gedit, which performs better over SSH. Either
way, be
sure to begin again at Section 4.4, where you will write your
rst Python program!
4.2 Working from the Sunlab or MSlab

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
fpunctuation 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:

4.1 Setting up
Runcs0160install pythonIntrofrom the command line. This will install a folder

Open the text editor Atom, by typingatom &in your terminal. First we will make
the .py
le you will write your program in.
1. Create a new
le: File>New File
2. Save this
le, File>Save, naming ithelloWorld.py. The .pyis very important!!
Make sure the
le is saved in your~/course/cs0160/pythonIntrodirectory.
We now need to con
gure 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 theEditor Settingssection. This is where you can con
gure
di#erent preferences for your Atom. Take a look at some of the options and feel
free
to play around with them.
Introduction to Python - 2018 March 4, 2018 2
CS 16
Introduction to Python - 2018
Introduction to Algorithms and Data Structures
2. Change theTab Lengthto be4and make sure theTab Typeis set to soft.
3. Close this tab and you're ready to go!
4.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.
Typegedit &into a terminal and press Enter to open Gedit.
First we will make the.py
le you will write your program in.
1. Save the current (blank) new
le: File>Save as...
2. Name the
lehelloWorld.py. The .pyis very important!! Make sure the
le is saved
in your ~/course/cs0160/pythonIntrodirectory.
Next, we have to con
gure Gedit to work well with Python.
1. Go toEdit->Preferences
2. Click on theEditortab
3. Ensure thatTab widthis set to 4
4. Check the box that saysInsert spaces instead of tabs
Close out of the preferences window. You're all set!
4.4 Let's get to coding!
From CS15, you are probably familiar with using these text editors to write Java
(.java)
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
fpunctuation 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:

4.1 Setting up
Runcs0160install pythonIntrofrom the command line. This will install a folder
Introduction to Algorithms and Data Structures
#! /usr/bin/python
at the top of yourhelloWorld.py
le. This tells your machine to use Python to interpret
the
le when executed. Then save the
le, go back to your terminal, and type chmod +x
helloWorld.pyto make the
le an executable. (If you haven't used chmodbefore, it's a
terminal command used to change
le permissions, in this case to make your Python
le
executable. The +xargument adds executability for the owner of the
le, you!) Now if
you type./helloWorld.pyinto your terminal your program prints Hello world! to the
terminal. From now on, all of your Python
les should start with#! /usr/bin/python.
5 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<name>!" Following the CS16 Python coding
conventions, the function would look like this:
def say_hello(name):
"""say_hello: string -> nothing
code. We'll be using them to write Python (.py)
les in CS16.
It's important you have con
gured your editor as speci
ed 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:
print `Hello world!'
and save your
le. Now go back to your terminal, make sure you are in thepythonIntro
directory and typepython helloWorld.pyto run the program. It will printHello world!
to your terminal.
Hold on, do you really have to typepython yourProgramName.pyevery time you want
to run a program? (Or for the especially lazy, scroll through your commands until
you
nd
the last time you typed it?) Heck no! Go back to your editor and type:
Introduction to Python - 2018 March 4, 2018 3
CS 16
Introduction to Python - 2018
Purpose: prints a greeting of the form "Hello <name>!"
Example: say_hello("Seny") -> "Hello Seny!"
"""
print "Hello " + name + "!" #this is the function body
When you de
ne a function in Python, you simply writedef(which is short for de
ne),
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

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 it

s beauty.
Python is similar to Java in that it 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, making your life a whole lot easier. If you're not already convinced that
Python
rules...
2 Why should 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
Introduction to Python - 2018
March 4, 2018 1
CS 16

Introduction to Python - 2018


Introduction to Algorithms and Data Structures
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 Day 1
Your journey through Python begins today...
4 Writing your
rst program in Python
It's tradition when learning a new programming language that your
rst program is a \Hello
World" program, so let's start out by writing a simple one-line program that prints
\Hello
World!"
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 adocstringand 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. First o#, it is indented four spaces
from
the function declaration. This is crucial. If you do not indent your code
correctly, it will
not work. Whitespace indentation is used in Python to nest blocks of code, rather
than
curly braces. Each subordinating code block must be indented four spaces relative
to the
code on which it depends. As you get used to programming in Python, this will
become
A snake! 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 di#erences from Java
that you
should note:
First, you don't need to declare the types of variables. Thus, you writex = 1rather
than int x = 1. Variables do have types, but you don't need to announce the type
when
you
rst use a variable. In fact, you can writex = 1and thenx = "abcd"in the same
program; after the
rst 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

You might also like