Session+1.2

=**Python First Steps: Input, Output and Variables**=

**Topics:**

 * Output: print statement
 * Interlude: two ways to run your script
 * Variables: integers, floating-point numbers (decimal), strings (text)
 * Numerical operations
 * Strings: quotes, single double and triple!
 * Strings: escapes and special characters; raw strings
 * Strings: as sequence type, index and slice (substring)
 * Concatenating (+) strings
 * Inserting and formatting variables in strings
 * Input: raw_input function

Introduction:
In this lesson, we will write our first programs. First we must learn how to interact with the Python language in a fundamental way, then we'll learn about different classes of data and how to manipulate them.

**A First Python Program: hello.py**
code format="python" print 'hello world' code

This code snippet (blocks of text in gray boxes like this indicate python code), when typed exactly as it appears above in an otherwise blank plain text file and saved (for instance, as //hello.py//) can be run from your shell prompt by typing "python hello.py" and hitting enter. Seriously--try it!

Let's start with a few simple steps, which will become ... super ... familiar.

1) Open a terminal window.

2) Make a new directory called //S1.2// for this afternoon's exercises and change to this directory: $ **mkdir S1.2 ** $ **cd S1.2**

3) Launch your text editor (Emacs or Aquamacs for most of you) as a background process: $ **emacs & ** or $ **aquamacs & **

By adding the ampersand (**//&//**), you keep control of your shell prompt after Emacs launches. If you don't use the ampersand, you'll need to open another terminal window in a moment to run our first program.

4) Code!

code format="python" print "hello world" code

Paste the above code snippet into your new document (or if you like to rock it old-school, type it for yourself!)

5) Save your new script: File->Save As type in your filename: //e.g.// //hello.py// click 'Save'

6) Go back to your terminal window, and run your script: $ **python hello.py** //hello world//

The meat of this script (in fact, the entirety of this script) is composed of the most basic python tool for communicating with the user, the **print** command. The print command essentially does exactly what it says: it outputs the statement that follows the word 'print' to the screen.

Unlike some other languages, in python print adds a newline character (a.k.a. "carriage return", a.a.k.a. "endline character") to the end of your print statement.

That means you see this output:

$ **python hello.py** //hello world// $

 instead of:

$ **python hello.py** //hello world//$

So print statements in python default to have the prompt reappear on the line below the output you've directed, as opposed to immediately after the printed statement. In general, this is handy. It does, however, mean that if you want two statements to be printed on the same line, you need to supply them to the same print statement, separated by commas. A space character will be inserted between the two (or more) statements thus supplied.

 If we change our program //hello.py//:

code format="python" print 'hello','world' code

then saving and running the modified program gives us:

$ **python hello.py** //hello world//

or, in other words, the result is exactly what we got the last time.

 For a little contrast, try:

code format="python" print 'hello' print 'world' code

Python's print statement can deal with pretty much anything you can cook up, including any of the variables or data types we discuss throughout this class. In a moment, we'll see that in addition to the strings (a string is a series of characters between quotes) you've been using, you could just as easily supply print with numbers or variables to display.

What happened here if you edited the original script and forgot to hit save?

**Informative Interlude: There are two ways to run your script**
While you have thus far successfully run at least three python programs by typing **python** followed by the name of the script, it might be nice to be able to run programs by simply typing the name of the program. To do so, we need to make two modifications to our script:

1) Add a line to the script referencing the python interpreter. This line is called a "shebang" because of the pair of characters used at the beginning of the line: the # ('sh' for "sharp") and the ! ('bang' for, well, sorta obvious reasons!).

So, add the following line to the very beginning of your script:

code format="python" code
 * 1) !/usr/bin/env python

(Don't forget to save!)

2) Change the file permissions on the script to include execute ('x'): $ **chmod +x hello.py**

The permissions for a file tell the operating system which users are allowed to read, write, or execute a file, as we learned in Session 1.1. The command we used in the line above, **chmod**, tells the operating system that it should let us execute the file (//hello.py//).

If we list the contents of our S1.2 directory, the command **ls** we will now see our script //hello.py// listed differently.

//hello.py*//
 * $ ls **

In most Linux environments, the file will be a pleasant shade of green. In Mac OS, a fiercely prepared red with a trailing asterisk indicates the executable status. Either way, there is something different about this file now: it is executable all on its own. We can take advantage of this by starting with the "dot-slash" characters, then typing the name of the file.

$ **./****hello.py** //hello world//

You certainly don't need to add the whole shebang and change all of your scripts to be executable; typing python to run your scripts is unlikely to materially contribute to your incipient repetitive stress injuries, but many people prefer to save the keystrokes.

This concludes this informative interlude.

**Variables: integers, floating-point numbers (decimal), strings (text)**

Computer programming is useful because it allows the programmer to tell the computer to perform operations that are too boring, tedious, or difficult for the programmer to do by hand. A useful computer program needs to be able to interact with the user, perform operations on changing sets of data, and make decisions about how to proceed based on conditions specific to each instance of its execution. To achieve these tasks, computer programs employ variables.

A variable is a datum with a human-readable name which can change values as the logic of the program dictates, as opposed to other types of data which have a constant, unchanging value once declared.

Python programs use variables to store parameters taken in from the user, the execution environment, or the data your program is being called upon to process. These variables are named whatever you like, within the strictures of a few basic rules: 1) Python variable names are case-sensitive, so **<span style="font-family: 'Courier New',Courier,monospace;">Var **and **<span style="font-family: 'Courier New',Courier,monospace;">var **are different variables. 2) Though variable names can contain letters, numbers and underscores ( **_** ), they MUST start with a letter (**a-z**). 3) Variable names, CANNOT contain spaces or special non-alphanumeric characters (//e.g.//**<span style="font-family: 'Courier New',Courier,monospace;"> holyS#+%? ** is naughty, but **<span style="font-family: 'Courier New',Courier,monospace;">holyMackerel ** is kid tested, mother approved), nor can they be any of the following words that already have special meaning in python:

code format="programlisting" and     assert   break    class    continue def      del      elif else    except   exec     finally  for      from     global   if         import   in       is       lambda   not      or       pass     print raise   return   try      while    yield code

For the most part, Emacs and Aquamacs will remind you that these words are off-limits by coloring these words in helpful ways when you type them.

Here are some invalid python variable names:

SampleA1
bootcamp_class

Variable types
Variables can hold all sorts of values, but will only hold one type of value at a time. Today we'll talk about three types of values: integers, floating point (//i.e.// decimal) numbers, and strings.

Run the following example, through which we'll explore a few properties of variables:

code format="python"
 * 1) !/usr/bin/env python
 * 2) we'll save this file as helloNorCal.py
 * 3) by the way, lines starting with the pound sign (#)
 * 4) makes them comments, ignored by the interpreter

s = 'hella world' i = 42 f = 3.14159 print s print 'the variable s is type',type(s)

print i print 'the variable i is type',type(i)

print f print 'the variable f is type',type(f)

code

And when we save and execute this file (don't forget to **chmod +x**, unless you want to type **python** before the program name), we get:

$ **helloNorCal.py** //hella world// //the variable s is type ‹type 'str'›// //42// //the variable i is type// //‹////type 'int'////›// //3.14159// //the variable f is type// //‹////type 'float'////›//

We begin the file with the shebang, which is optional. Then a few lines starting in #, which are comments. As you write your own code, use commented lines to describe what bits of code do and how they do it (we'll discuss this in more detail later in the week).

Then come our assignments:

code format="python" s = 'hella world' i = 42 f = 3.1412

code

In general, variables are //assigned// by typing the name you want to use, followed by a single equals sign, then the value you'd like to store. This is the same whether the variable you're assigning is of type <span style="font-family: 'Courier New',Courier,monospace;">**str** (a character string), <span style="font-family: 'Courier New',Courier,monospace;">**int** (whole number), **<span style="font-family: 'Courier New',Courier,monospace;">float ** (non-integer real number), or any number of other fancier things you'll be using in the next two weeks.

While (as your program tells you with the handy **<span style="font-family: 'Courier New',Courier,monospace;">type ** function) that **<span style="font-family: 'Courier New',Courier,monospace;">i ** is currently an integer, that doesn't mean it cannot change. You can easily reassign **<span style="font-family: 'Courier New',Courier,monospace;">i ** to be anything that takes your fancy, including the value of another variable. You would do this with a statement such as the following:

code format="python" i = s

print i print 'the variable i is now type',type(i) code

The output of these statements will exactly mirror that of the statements earlier using the variable **<span style="font-family: 'Courier New',Courier,monospace;">s ** since **<span style="font-family: 'Courier New',Courier,monospace;">i ** was re-assigned (after it was initially printed, etc) to the value of **<span style="font-family: 'Courier New',Courier,monospace;">s. **

There are plenty of cases where this is exactly what you want to do, but bear in mind that once no more variables are assigned any particular value, that value is lost forever.

As an example, consider the case where (for some reason) you want to swap the values of two variables <span style="font-family: Arial,Helvetica,sans-serif;">**s** and **i**. The first step might appear to be a line very much like the <span style="font-family: 'Courier New',Courier,monospace;">**i = s** statement above, but if you do this, the value of <span style="font-family: 'Courier New',Courier,monospace;">**i** is lost forever, meaning you can never assign it to <span style="font-family: 'Courier New',Courier,monospace;">**<span style="font-family: 'Courier New',Courier,monospace;">s **. This may seem like a rather abstract problem, (unless you've read ahead to today's exercises) but you'll encounter similar situations more often than you might think.

Numerical operations
Numerical values can be subjected to a wide variety of operations. While the full list is quite extensive (see [] for the full workup), the most common operations should be familiar. For the most part, we use basic arithmetic operators exactly as you're used to seeing them:

code format="python"
 * 1) !/usr/bin/env python

i = 42 f = 3.14159

sum = i + f diff = i - f prod = i * f quo = i / f pow = i ** f
 * 1) addition uses the plus sign (+)
 * 1) subtraction uses the minus sign (-)
 * 1) multiplication uses the asterisk (*)
 * 1) division uses the slash (/)
 * 1) and exponents use a double-asterisk (**)

print 'sum',sum print 'diff',diff print 'prod',prod print 'quo',quo print 'pow',pow

x = 5 print "x", x x += 1 print "now x is one more than before", x

code

And when we save and execute:

$ **hellaNorCal.py** //sum 45.14159// //diff 38.85841// //prod 131.94678// //quo 13.3690265121// //pow 125771.933736// //x 5// //x 6//

Note that standard mathematical order of operations applies, but it's far easier ... and safer ... to explicitly order compound operations using parentheses.

String quotes: single, double, and triple!
As mentioned, strings are specified by wrapping a series of characters in quotes. These can be quotes of three different flavors. The first two, single (a.k.a. the apostrophe) and double, are familiar (although don't confuse the single quote (**'**) with the backtick (**`**) -- the one that's probably with the tilde (**~**) on your keyboard).

Single and double quotes can more or less be used interchangeably, the only exception being which type of quote is allowed to appear //inside// the string. If the string itself is double-quoted, single quotes may appear inside the string, and visa-versa:

code format="python"
 * 1) !/usr/bin/env python

s = 'hello "world", if that is your real name.' print s s2 ="That's World, to you, buddy." print s2

code

$ **hello.py** //hello "world", if that is your real name.// //That's World, to you, buddy.//

The key things to notice here are that double quotes are present in the first, and a single quote appears in the second, but the two cannot be combined. In order to use both single and double quotes in the same print statement, employ the extra-spiffy triple quote, which is actually just three single quotes:

code format="python"
 * 1) !/usr/bin/env python

s = '''hello "world", if that is your real name. That's World, to you, buddy.'''

print s

code

$ **hello.py** //hello "world", if that is your real name.// //That's World, to you, buddy.//

This snippet does //almost// exactly the same thing as the last snippet.

Note two aspects of the triple quotes: 1) Both single and double quotes can be used inside triple quotes. 2) Triple quoted strings can span multiple lines, and line breaks inside the quoted string are stored and faithfully displayed in the **<span style="font-family: 'Courier New',Courier,monospace;">print ** operation.

Strings: escapes and special characters; raw strings
Try the following code snippet:

code format="python"
 * 1) !/usr/bin/env python

s = 'some\thing is missing' print s s2 = "somethi\ng is broken" print s2 s3 = something th\at will drive you b\an\an\as print s3

s4 = r'\a solu\tio\n' print s4

s5 = '\\another solu\\tio\\n' print s5

code

And you'll be treated to the following gibberish:

$ **hello.py** //some hing is missing// //somethi// //g is broken// //something tht will drive you bnns// //\a solu\tio\n// //\another solu\tio\n//

This ugly (and possibly loud, if your sound is working properly) mess is caused by //escape characters//. In python strings, several special characters (full list here: [|http://docs.python.org/ref/strings.html]) can be preceded by a backslash (**\**) to produce special output, such as a tab (**\t**) newline (**\n**) or even a bell noise **(\a**).

This is handy, since it means you can liberally pepper your strings with tabs and line breaks. In fact, lots of the data that we use are conveniently stored in files that are delimited by such tabs and line breaks. This might be a problem, however, say if you wanted to use a backslash in your string. Python offers two ways around this: the safest is to escape your escape, using a second backslash (see s5 above, '\\'). A fancier way involves a special kind of string, the raw string.

Raw strings start with **<span style="font-family: 'Courier New',Courier,monospace;">r' ** and end with **<span style="font-family: 'Courier New',Courier,monospace;">' ** and will treat every character between as exactly what it looks like, with the exception of the single quote (which ends the string). If you do use raw strings, watch out for two catches: 1) You must still escape single quotes you want to appear inside the string. 2) The last character of the string cannot be a backslash, since this will escape the closing quote.

code format="python"
 * 1) !/usr/bin/env python

s6 = r'but there ain\'t a problem with this' print s6
 * 1) s6 = r'don't do this'

s7 = r'but this is okay\ ' print s7 code
 * 1) s7 = r'this is bad\'

There are proper times and places for the use of the raw string method, but in general we recommend just escaping your backslashes. As a final point on escapes, **<span style="font-family: 'Courier New',Courier,monospace;">\' ** and **<span style="font-family: 'Courier New',Courier,monospace;">\" ** provide a means to employ single quotes inside a single quoted string, and likewise double quotes in a double quoted string.

Strings: as sequence type, index and slice (substring)
Strings are merely successions of characters, and python stores and operates on them as such. The official python lingo for something that can be operated on as an ordered series of sub-elements is a 'sequence'. While several python data types are sequences, strings are the only one we'll deal with today. In the next couple of days, however, some of the notation you learn today will come back in other contexts.

The first property of sequences we'll look at is indexing.

code format="python"
 * 1) !/usr/bin/env python
 * 2) We'll save this file as names.py

name = 'Nathaniel I. Krefman' middle_initial = name[10] # variable[i] is the ith index of variable.
 * 1) (Yeah, comments can be on the same line as other stuff,
 * 2) but's it's recommended that you keep them on their own lines.)

print name print middle_initial

code

Running the script yields: $ **names.py** //Nathaniel I. Krefman// //I//

Here you've stored a string (my full name), then used a property of sequences, //indexing//, to ask for a particular character in that string. In the code you see that I've asked for the 10th character in the string, which unless you're a bit odd you'd probably say was the space (since space IS a character) between 'Nathaniel' and 'I'. The reason 'I' is the 11th character lies in a generalism of python sequences:

//**NUMBERING STARTS AT ZERO**//

Yeah. This is important. //**BOLD CAPITALS AND ITALICS**// kinds of important.

Using indexing, it's possible to pick out any number of individual characters in this manner and stitch them back together as substrings, but sequences can also be operated on in contiguous subsets of indices, called //slices//. Slices look like indices, except with two numbers separated by a colon. The slice starts at the index of the first number, and ends at the index //before// the second number, so in the example above **<span style="font-family: 'Courier New',Courier,monospace;">name[9:13] ** would be ' I. ' (middle initial, period, and both flanking spaces). This lets us do handy things like: code format="python"
 * 1) !/usr/bin/env python

name = 'Nathaniel I. Krefman' middle_initial = name[11]

first = name[0:9]
 * 1) the start of the sequence to the end of my first name

last = name[13:] print name print last print middle_initial print first
 * 1) omitting the second number (but using the colon)
 * 2) goes to the end of the string

code

$ **hello.py** //Nathaniel I. Krefman// //Krefman// //I// //Nathaniel//

A key time saver here is that omission of the first number starts at the beginning of the sequence, and omission of the second number goes all the way to the end. Of course, this only works if the colon is there, otherwise you just get an index.

Concatenating (+) strings
At this point you've merrily sliced away at my good name; time to put me back together again. Python offers a simple operator for putting strings together: +

We will refer to this operation as string //concatenation.//

code format="python"
 * 1) !/usr/bin/env python

name = 'Nathaniel I. Krefman' middle_initial = name[11] first = name[0:9] last = name[13:]

print name

simple_name = first + ' ' + last last_first = last + ', ' + first + ' ' + middle_initial + '.' print simple_name print last_first

simple_name_also = first, last

code

$ **names.py** //Nathaniel I. Krefman// //Nathaniel Krefman// //Krefman, Nathaniel I.//


 * +** basically does what you might imagine and its use is fairly straightforward, but it is oddly similar to another operator we've seen. You know…the plus sign. The difference between string concatenation and numerical addition is only whether the values on either side are strings or numbers. Thus, using one of each, like 'string' **+** 5 will confuse the crap out of python, and therefore should be avoided. If you meant to concatenate 'string' and the string '5' to get 'string5', the section on inserting and formatting variables in strings will allay your woes.

**Coercion**
If you had instead somehow managed to get a number like '5' stored as a string (for instance, you took it as input from a file or user), then you would need a way to convince python to let you use the number as…well…a number! Your tools for this are //coercion functions//. You'll see these again and in more detail tomorrow, but for now just know that if something looks like a number, but has quotes around it, the functions**<span style="font-family: 'Courier New',Courier,monospace;"> int ** and**<span style="font-family: 'Courier New',Courier,monospace;"> float ** will give you back real numbers to play with. Use them like so:

code format="python" integer_text = '5' decimal_text = '3.14'

print integer_text + decimal_text

integer = int(integer_text)


 * 1) this next one would be trouble--uncomment to get your very own python bug!
 * 2) print integer + decimal_text

decimal = float(decimal_text)

print integer + decimal code

$ **names.py** //53.14// //8.14//

You're welcome to mess with these a little bit (try **<span style="font-family: 'Courier New',Courier,monospace;">type(integer_text) ** and <span style="font-family: 'Courier New',Courier,monospace;">**type(integer**) from earlier, for instance), but their use is incredibly straightforward. Just remember, if you see a <span style="font-family: 'Courier New',Courier,monospace;">TypeError when you try to run a script, this should be the first thing you look for!

Inserting and formatting variables in strings
The final string topic we'll discuss is the specific formatting and insertion of variables into strings. In **<span style="font-family: 'Courier New',Courier,monospace;">last_first ** in the previous example, we added additional characters to the variables we were stitching together by a bunch of concatenations, adding characters like space, commas and periods. The other method python offers, called //string interpolation//, for injecting variables into strings looks like the following:

code format="python" last_first = '%s, %s %s.' % (last, first, middle_initial) code

This handily replaces all those **+** operations with a very readable string, where **<span style="font-family: 'Courier New',Courier,monospace;">%s ** represents spots where the variables or values you supply next will be inserted, in the order you supply them. After the string comes a solitary **<span style="font-family: 'Courier New',Courier,monospace;">% **, then a set of values in parentheses. These are the values to interpolate, and there must be as many of these as there are **<span style="font-family: 'Courier New',Courier,monospace;">%s ** elements in your string. This is a nice way of composing a string of other strings, but its a downright blessing when you want to compose a string including number values. In the case of numbers, you can always supply them to strings with **<span style="font-family: 'Courier New',Courier,monospace;">%s ** elements (like we just did with string variables), but there are also special interpolation operators for numbers**<span style="font-family: 'Courier New',Courier,monospace;"> %d ** and**<span style="font-family: 'Courier New',Courier,monospace;"> %f ** (corresponding to integer and floating point, respectively). For a full workup, see [], but here's a start:

code format="python"
 * 1) !/usr/bin/env python

i = 42 f = 3.14159265

string = 'variables can be interpolated as strings here %s and here %s' % (i,f) print string

print '''To get 2 decimal places write %.2f, or to get 2 decimal places padded to a total width of 5, write [%5.2f] (notice that the '.' counts as a character). The brackets above don't do anything--they're just there to point out to you the left padding; you can replace the spaces in the second example with zeros this way: %07.3f.''' % (f,f,f)
 * 1) Remember how we said returns are faithfully reproduced from triple quoted strings?

code

$ **names.py** //variables can be interpolated as strings here: 42 and here 3.14159265// //To get 2 decimal places write 3.14, or to get 2 decimal places padded// //to a total width of 5t, write [ 3.14] (notice that the '.' counts as a character).// //The brackets above don't do anything--they're just there to point out to you the// //left padding; you can replace the spaces in the second example with zeros this// //way: 003.142.//

Practically speaking, the most commonly used formatting tools are **%s** to shove variables of any and all types into strings, and **%.xf** where x is the number of decimal places to display for floating point numbers. Most commonly, you will see and employ a lot of '**%.2f**' string interpolations, and almost never see or use any of the other numerical interpolators.

(More detailed documentation about the various interpolation options can be found in the [|python documentation])

Input: raw_input function
Lastly, we need a way to get data //into// a program. While there are several ways to gather data from the outside world, the simplest is to just ask. In python, a program asks for information from the user with the **<span style="font-family: 'Courier New',Courier,monospace;">raw_input ** function, as demonstrated here:

code format="python"
 * 1) !/usr/bin/env python
 * 2) hello whoever you are!

user = raw_input("what's your name? ") print 'hello %s!' % (user)

code

I'll let you figure out what this looks like...

The **<span style="font-family: 'Courier New',Courier,monospace;">raw_input ** function prompts the user by printing to the screen whatever value is given in the parentheses immediately following the **<span style="font-family: 'Courier New',Courier,monospace;">raw_input ** call, (in this case asking "what's your name?") and then waits for the user to type whatever they want for as long as they feel like, until the user hits enter. **<span style="font-family: 'Courier New',Courier,monospace;">raw_input ** (which is a //function//, like **<span style="font-family: 'Courier New',Courier,monospace;">int ** or **<span style="font-family: 'Courier New',Courier,monospace;">float **, a topic we'll talk a lot more about later) then takes everything up until the user hits enter and //returns// that as a string. Again, we'll talk more about this idea, but here all you need to know is that **<span style="font-family: 'Courier New',Courier,monospace;">raw_input ** gives back the user's input as a string, and that gets saved to the variable **<span style="font-family: 'Courier New',Courier,monospace;">user ** using the assignment operator (**=**). This should be easy stuff at this point. After taking this input, we just spit it right back out (emplying the string interpolation trick we learned a few minutes ago).

Now that you know everything you need to know to accept basic input, manipulate numbers and strings, store them in variables, and generate meticulously formatted output…try these practice exercises!

=**Exercises:**=

**1: The Greeter**

 * Write a program that asks for the user's name tells them hello.

**2: What's My Age Again?**

 * Ask for their year of birth and compute their age.
 * Print out their age in the following format:

**3: Ratio**

 * Read two numbers in (user input).
 * Print out their ratio.
 * Figure out how to make this program fail. (There are many ways.)

**4: Sum and Mean**

 * Read five numbers in.
 * Print out their sum and mean.

**5: Swap**
= = =**Challenges:**=
 * The user enters two numbers.
 * Store the numbers in two variables called input1 and input2.
 * Swap the values of the two variables so that input1 has the value of input2 and vice versa.
 * Print out the two variables.

**6: Quickswap**

 * Perform the swap in #5 above in only 1 line of code, and without using any variables other than input1 and input2. (Hint: you need tuples; try Google!)

**7: Index-tastic**

 * Ask the user to specify a number of digits (//e.g.// 1-digit numbers, 2-digit numbers, //etc.//).
 * Ask the user to supply five numbers of that many digits separated by spaces.
 * Parse these numbers out, and calculate sum and mean as in Exercise #4.
 * Try doing this without using any additional variables! (Use only the one that contains the string that you read in.)

**8: Escape!**
code format="python" s = '''hello "world", if that is your real name. That's World, to you''' code in just one string using single or double quotes. Make sure you have the line break and all the quotes and apostrophes in there!
 * Reproduce the triple-quoted string from earlier:

1) The Greeter
code format="python"
 * 1) !/usr/bin/env python

name = raw_input("Hey, what's your name? ")
 * 1) It's nice to format the prompt and give people directions when
 * 2) asking them to input text


 * 1) If you don't want print to put a space after everything in the series
 * 2) of comma-separated printables, then concatenate them with a plus-sign
 * 3) like I've done here to get the ! after the name without a space

print "Well, hello there", name + "!"

code

2) What's My Age Again?
code format="python"
 * 1) !/usr/bin/env python

year = int( raw_input("Hey, what year were you born? ") )

print "Sooooo, let's see..." print "you must be about", str((2012 - year)) + "."

code

3) Ratio
code format="python"
 * 1) !/usr/bin/env python


 * 1) if we make them floats, then we avoid integer truncation (one way to break it)

num1 = float(raw_input("Enter a number and press return: ")) num2 = float(raw_input("Now enter another number and press return: "))

print "The ratio of these two numbers is", (num1 / num2), "to 1."

code

4) Sum and Mean
code format="python"
 * 1) !/usr/bin/env python

print "Enter five numbers, pressing return after each number:" num1 = float(raw_input("Number 1: ")) num2 = float(raw_input("Number 2: ")) num3 = float(raw_input("Number 3: ")) num4 = float(raw_input("Number 4: ")) num5 = float(raw_input("Number 5: "))

sum = num1 + num2 + num3 + num4 + num5 mean = sum / 5

print "The sum of these numbers is", str(sum) + "." print "And the mean is", str(mean) + "."

code

5) Swap
code format="python"
 * 1) !/usr/bin/env python

input1 = float(raw_input("Please enter a number and press return:\n")) input2 = float(raw_input("Please enter another number and press return:\n"))

tmp = input1 input1 = input2 input2 = tmp

print "Ohhh, so you entered", str(input1), "and", str(input2)

code

6) QuickSwap
code format="python"
 * 1) !/usr/bin/env python

input1 = float(raw_input("Please enter a number and press return:\n")) input2 = float(raw_input("Please enter another number and press return:\n"))


 * 1) If you googled for tuples and quick swap, you hopefully read something about "tuple packing"
 * 2) This is not available in most programming languages, in that you are assigning input2 to input1
 * 3) and input1 to input2 simultaneously (i.e. from left to right as ordered pairs across the equals sign)

input1, input2 = input2, input1

print "Ohhh, so you entered", str(input1), "and", str(input2)

code

**7) Index-tastic**
code format="python"
 * 1) !/usr/bin/env python

diglen = int(raw_input("Please enter a digit length and press return\n"))
 * 1) get our length

numstr = raw_input("Please enter 5 integers of the length you specified separating each by a space.\n")
 * 1) get our numbers

idx = diglen
 * 1) create an idx variable that can change as we move through the str with slices

num1 = numstr[0:idx] idx += 1
 * 1) gotta start off by moving one spot

num2 = numstr[idx: idx + diglen] idx += diglen + 1
 * 1) then we're going to move by the diglen and one more
 * 2) this should work until the last one

num3 = numstr[idx: idx + diglen] idx += diglen + 1

num4 = numstr[idx: idx + diglen] idx += diglen + 1

num5 = numstr[idx:]
 * 1) And the last one just print to the end of the str

print num1 print num2 print num3 print num4 print num5


 * 1) BELOW FOLLOWS AN ALTERNATE SOLUTION FOR THIS PROBLEM THAT INCLUDES THE ONE-LINE SOLUTION:

digits = int(raw_input('Specify a number of digits: ')) + 1 cluster_f = raw_input('Please specify 5 numbers contain %s digits each, separated by spaces: ' % (digits)) one = int(cluster_f[0:digits]) two = int(cluster_f[digits:2*digits]) three = int(cluster_f[2*digits:3*digits]) four = int(cluster_f[3*digits:4*digits]) five = int(cluster_f[4*digits:5*digits]) print 'One is', one print 'Two is', two print 'Three is', three print 'Four is', four print 'Five is', five sum = one + two + three + four + five print 'The sum is %s.' % (sum) mean = sum / 5 print 'The mean is %s.' % (mean) print
 * 1) user will specify a number of digits and 5 numbers separated by a space of that number of digits

digits2 = int(raw_input('Specify a number of digits: ')) + 1 cluster_f2 = raw_input('Please specify 5 numbers contain %s digits each, separated by spaces: ' % (digits2)) print int(cluster_f2[0:digits2]) + int(cluster_f2[digits2:2*digits2]) + int(cluster_f2[2*digits2:3*digits2]) + int(cluster_f2[3*digits2:4*digits2]) + int(cluster_f2[4*digits2:5*digits2]) print
 * 1) a solution using one line without introducing extra variables

code

8) Escape!
code format="python"
 * 1) !/usr/bin/env python

s = "hello \"world\", if that is your real name.\nThat\'s World, to you" print s

code