[Tutor] New to Python
steve at pearwood.info
Mon Apr 28 20:52:08 CEST 2014
On Sat, Apr 26, 2014 at 03:53:33PM -0700, jordan smallwood wrote:
> I am new to Python. I mean completely new and we're working on this
> problem set in class where they give us specs and we have to build
> something based off these specs. I have no idea what they're asking.
> Could someone help get me started on the path to figuring this out?
Yes. You need to write two functions, one to convert from inches to
centimetres and one from centimetres to inches. You've learned about
functions in maths class, I expect. This is similar.
Here's how you write functions in Python.
"""Return double x."""
"""Return half of x, plus 1."""
return x/2.0 + 1
The keyword "def" starts the definition of the function. It is followed
by the name of the function, then inside round brackets (parentheses) is
a list of the arguments that the function requires. In my examples, the
function only takes one argument, x, which you can assume is a number.
If possible, you should use a more descriptive name than "x".
The next line, a string starting and ending with THREE quotation marks,
is called a "doc string". It's just a short comment explaining what the
function does. (It's also optional, but recommended.)
Inside the function, all your code needs to be indented by one level.
You should indent by either:
Four spaces (this is recommended)
One Tab (if you must)
although any number of spaces is allowed, so long as it is consistent.
Whatever you use, pick one, and use it for all indentation. Python will
complain, or worse, do the wrong thing, if you have inconsistent
indentation. (Say, four spaces on one line, then three on the next.)
Both my functions are simple enough that I only have a single line. The
keyword "return" tells Python what value should be returned. It should,
I hope, be obvious that 2*x gives two times x.
Is that enough to get you started?
More information about the Tutor