Python First Steps: Input, Output and Variables


  • 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


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

A First Python Program:

print 'hello world'

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 can be run from your shell prompt by typing python 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 for this afternoon's exercises, and change to that directory:
$ mkdir S1.2
$ cd S1.2

3) Launch Emacs as a background process:
$ emacs &

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!

print "hello world"

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

5) Save your new script
File->Save As
type in your filename: ""
click Save

6) Go back to your terminal window, and run your script:
$ python
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 world

instead of:

$ python
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

print 'hello','world'

then saving and running the modified program gives us:

$ python
hello world

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

For a little contrast, try:

print 'hello'
print 'world'

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 (series of characters between quotes) you've been using, you could just as easily supply print with numbers or variables to display.

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:
#!/usr/bin/env python
(don't forget to save!)
2) Change the file permissions on the script to include execute ('x'):
$ chmod +x
The permissions for a file tell the operating system which users are allowed to read, write, or execute a file. The command we used in the line above, chmod, tells the operating system that it should let us execute the file
If we list the contents of our S1.2 directory the command ls we will now see our script listed differently.

$ 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 world

You certainly don't need to add the 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 the I.I.

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 without joining the ranks of the faithfully insane. For a computer program 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, it employs 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 once declared have a constant, unchanging value. 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 Var and var are different variables. 2) Though variable names can contain letters, numbers and underscores ( _ ), they names MUST start with a letter (a-z). 3) Variable names, CANNOT contain special characters (+, -.\ etc.), nor can they be any of the following words that already have special meaning in python:==
         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

For the most part, Emacs 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:




And here are some good alternatives:




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:
#!/usr/bin/env python
# we'll save this file as
# by the way, lines starting with pound signs (#)
# are comments, ignored by the interpreter
s = 'hello world'
i = 42
f = 3.14159
print s
print 'is type',type(s)
print i
print 'is type',type(i)
print f
print 'is type',type(f)
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:

hello world
is type ‹type 'str'›
is type type 'int'
is type type 'float'

We begin the file with the shebang, which is optional. Then a few lines starting in #, which are comments. Use commented lines to describe what bits of code do and how they do it (more detail on this later in the week).

Then come our assignments:
s = 'hello world'
i = 42
f = 3.1412
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 str (a character string), int (whole number), 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 type() function) that i is currently an integer, that doesn't mean it cannot change. You can easily re-assign 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:
i = s
print i
print 'is type',type(i)
The output of these statements will exactly mirror that of the statements earlier using the variable s since i was re-assigned (after it was initially printed, etc) to the value of 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 s and i. The first step might appear to be a line very much like the i = s statement above, but if you do this, the value of i is lost forever, meaning you can never assign it to 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:
#!/usr/bin/env python
i = 42
f = 3.14159
# addition uses the plus sign (+)
sum = i + f
# subtraction uses the minus sign (-)
diff = i - f
# multiplication uses the asterisk (*)
prod = i * f
# division uses the slash (/)
quo = i / f
# and exponential powers use a double-asterisk (**)
pow = i ** f
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
And when we save and execute:

sum 45.14159
diff 38.85841
prod 131.94678
quo 13.3690265121
pow 125771.933736

Note that standard 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 above the tilde).

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 is double-quoted, single quotes may appear inside the string, and visa-versa:
#!/usr/bin/env python
s = 'hello "world", if that is your real name.'
print s
s2 ="That's World, to you, buddy."
print s2

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. The tool to use here is the extra-spiffy triple quote, which is actually just three single quotes:
#!/usr/bin/env python
s = '''hello "world", if that is your real name.
That's World, to you, buddy.'''
print s
This snippet does 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 print operation.

Strings: escapes and special characters; raw strings

Try the following code snippet:
#!/usr/bin/env python
s = 'some\thing bad'
print s
s2 = "somethi\ng else bad"
print s2
s3 = '''something \also bad'''
print s3
s4 = r'\a solu\tio\n'
print s4
s5 = '\\another solu\\tio\\n'
print s5
And you'll be treated to the following gibberish:
some hing bad
g else bad
something lso bad
\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, there are several special characters (full list here: 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, and lots of our data are conveniently stored in files that are delimited by tabs and line breaks. This might also be a problem, say if you wanted to use a backslash in your string. Python offers two ways around this: the safest is to escape your escape, again with a backslash (see s5 above, '\\'). A fancier way involves a special kind of string, the raw string.

Raw strings start with r' and end with ' 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.

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, \' and \" 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.
#!/usr/bin/env python
# we'll save this file as
name = 'Matthew D. Davis'
middle_initial = name[8] # variable[i] is the ith index of variable.
# (Yeah, comments can be on the same line as other stuff,
# but's it's recommended that you keep them on their own lines.)
print name
print middle_initial
Matthew D. Davis

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 8th character in the string, which unless you're a bit odd you'd probably say was the space (since space IS a character) between 'w' and 'D'. The reason 'D' is the 8th character lies in a generalism of python sequences:


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 name[7:11] would be ' D. ' (middle initial, period and both flanking spaces). This lets us do handy things like:
#!/usr/bin/env python
name = 'Matthew D. Davis'
middle_initial = name[8]
#the start of the sequence to the end of my first name
first = name[0:7]
# omitting the second number (but using the colon)
# goes to the end of the string
last = name[11:]
print name
print last
print middle_initial
print first

Matthew D. Davis

A key timesaver 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.
#!/usr/bin/env python
name = 'Matthew D. Davis'
middle_initial = name[8]
first = name[0:7]
last = name[11:]
print name
simple_name = first + ' ' + last
last_first = last + ', ' + first + ' ' + middle_initial + '.'
print simple_name
print last_first

Matthew D. Davis
Matthew Davis
Davis, Matthew D.

+ 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 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.


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 int() and float() will give you back real honest-to-pete numbers to play with. Use them like so:
integer_text = '5'
decimal_text = '3.14'
print integer_text + decimal_text
integer = int(integer_text)
# this next one would be trouble--uncomment to get your very own python bug!
# print integer + decimal_text
decimal = float(decimal_text)
print integer + decimal


You're welcome to mess with these a little bit (try type(integer_text) and type(integer) from earlier, for instance), but their use is incredibly straightforward. Just remember, if you see a 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 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:
last_first = '%s, %s %s.' % (last, first, middle_initial)
This handily replaces all those + operations with a very readable string, where %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 %, then a set of values in parentheses. These are the values to interpolate, and there must be as many of these as there are %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 %s elements (like we just did with string variables), but there are also special interpolation operators for numbers %d and %f (corresponding to integer and floating point, respectively). For a full workup, see , but here's a start:
#!/usr/bin/env python
# str%dngthing % (1)
i = 42
f = 3.14159265
string = 'variables can be interpolated as strings here: %s and here %s' % (i,f)
print string
print '''2 decimal places: %.2f, or 2 decimal places padded
to a total width of 5: [%5.2f] (note that the '.' counts as a character).
The brackets above don't do anything--they're just there to show the left padding
again, but using 0's: %07.3f''' % (f,f,f)

variables can be interpolated as strings here: 42 and here 3.14159265
2 decimal places: 3.14, or 2 decimal places padded
to a total width of 5: [ 3.14] (note that the '.' counts as a character).
The brackets above don't do anything--they're just there to show the left padding
again, but using 0's: 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 raw_input() function, as demonstrated here:
#!/usr/bin/env python
# hello whoever you are!
user = raw_input("what's your name? ")
print 'hello %s!' % (user)
I'll let you figure out what this looks like...

The raw_input() function prompts the user by printing to the screen whatever value is given in the parentheses immediately following the 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. raw_input (which is a function, like int() or float() and is something 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 raw_input gives back the user's input as a string, and that gets saved to the variable user using the assignment operator (=), this should be easy stuff at this point. After taking this input, we just spit it right back out (using 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!


1: The Greeter

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

2: Is that rude?

  • Ask for their year of birth and compute their age.
  • Print out their age in the following format:
Your age is 25.

3: Ratio

  • Read two numbers in (user input)
  • Print out their ratio.
  • Figure out how to make this program fail.

4: Sum and Mean

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

5: Swap

  • 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 5 numbers of that many digits separated by spaces
  • parse these numbers out, and calculate sum and mean as in #4
  • Try doing this without using any additional variables! (just the one that contains the string you read in)

8: Escape!

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


1) The Greeter

#!/usr/bin/env python
# It's nice to format the prompt and give people directions when
# asking them to input text
name = raw_input("Hey, what's your name?\n [Press return after entering your name]\n")
# If you don't want print to put a space after everything in the series
# of comma-separated printables, then concatenate them with a plus-sign
# like I've done here to get the ! after the name without a space
print "Well, hello there", name + "!"

2) Is that rude?

#!/usr/bin/env python
year = int( raw_input("Hey, what year were you born?\n [Press return after entering year]\n") )
print "Sooooo, let's see..."
print "you must be about", str((2009 - year)) + "."

3) Ratio

#!/usr/bin/env python
# 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."

4) Sum and Mean

#!/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) + "."

5) Swap

#!/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)

6) QuickSwap

#!/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"))
# If you googled for tuples and quick swap, you hopefully read something about "tuple packing"
# This is not available in most programming languages, in that you are assigning input2 to input1
# 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)

7) Index-tastic

#!/usr/bin/env python
# get our length
diglen = int(raw_input("Please enter a digit length and press return\n"))
#get our numbers
numstr = raw_input("Please enter 5 integers of the length you specified separating each by a space.\n")
#create an idx variable that can change as we move through the str with slices
idx = diglen
num1 = numstr[0:idx]
#gotta start off by moving one spot
idx += 1
num2 = numstr[idx: idx + diglen]
# then we're going to move by the diglen and one more
# this should work until the last one
idx += diglen + 1
num3 = numstr[idx: idx + diglen]
idx += diglen + 1
num4 = numstr[idx: idx + diglen]
idx += diglen + 1
#And the last one just print to the end of the str
num5 = numstr[idx:]
print num1
print num2
print num3
print num4
print num5
# user will specify a number of digits and 5 numbers separated by a space of that number of digits
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)
# a solution using one line without introducing extra variables
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])

8) Escape!

#!/usr/bin/env python
s = "hello \"world\", if that is your real name.\nThat\'s World, to you"
print s