Friday, September 6, 2013

Python Intro

repl.it
So you've finally decided you want to learn to program.  Or maybe you know how to program but you want to learn Python.  In either case, this tutorial is for you!  This is for complete Python beginners.



Python logo
Before you can write and use any Python, you need to find an application that will run your code.  For expediency's sake I will skip over installing and running Python natively; we'll use repl.it (a free online interpreter) instead.  This guide is written for Python 2, so if you have Python 3 installed just use repl.it.  Navigate to repl.it, click the languages button (the leftmost button in the top right corner of the screen) and set it to Python, then click anywhere in the area of the screen on the right side with the blue background.  Now let's write some code!

To start off, type:
print "Hello world!"
and press Enter.

You should see this:






You just added to a 41 year old tradition and wrote your first Python program!  Well done.
The "Hello World" example illustrates the usage of Python's print statement.  To print a string (a collection of zero or more characters delineated by quotation marks, like "Yolo swag", "hello", "5.24" or "D"), type print followed by the phrase you wish to print enclosed in quotation marks.  Here are some more examples of print:
print "Size matters not - Yoda"
print 42
print "It's a great day to be alive!"
Play around with the interpreter.  See what works and what doesn't.  Try printing numbers, fractions or punctuation.  Try using single quotation marks on strings.

Python (like every other good programming language) lets us save values to variables for later use.  Think of a variable like a box.  A box can hold books, toys or video games and a variable can hold strings, integers and doubles (plus much more).  To save a value to a variable, type a variable name followed by an equals sign (=) followed by the value you wish to save.  For example:
x = 42
Now the variable x holds the value 42.  We can verify this by printing x:
x = 42
print x
You can print variables in much the same way that you can print numbers or strings.  Try the above example, then play around with the interpreter.  Here are some more examples to help you get the hang of the syntax:
the_answer = 42
price = 1.95
userName = "macsj200"
x = price
elephant_name = "Dumbo"
Try setting x to a different string, or a number.  Try creating other variables.  Try setting x equal to another variable.  Try printing variables before you create them.  Use the print statement to see the results of your actions.

Python variables must start with a letter and be only one word, but other than that name then whatever you want.  It is a good idea to get into the habit of giving your variables meaningful names, like speed or priceOfIitem or number_of_cans instead of x or zs.  Food for thought: what is the difference between print x and print "x"?

Click here to go to Part 2

No comments:

Post a Comment