You are on page 1of 15

A Beginners Guide to Python

Python Version: 3.3.4


Contents
For Starters (IDLE)
Hello World!
Variables
Operators
The IF statement
ElseIF and Else
Functions
Arguments
For Loop
While Loop
Strings
Lists
Tuples
For Starters
Python IDLE (shown right)
On installation, IDLE (Python GUI) should be found in your start
menu files
On Windows 7: Start > All Programs> Python 2.7> IDLE
On Windows 8: Start > All Apps > Python 2.7> IDLE
Python can be programmed in any text editor and
saved as a .py file, but for the sake of this tutorial,
we will be using the interpreter to cover the python
syntax(the way it is written) and other basic
programming concepts.
Note that the interpreter functions like a command
prompt in Windows. You cannot delete items once
the ENTER key is pressed. Mistakes should be of no
concern, howeverif an error occurs simply try
again on the next line until you get the desired
output, or restart IDLE if youd like to work from a
clean slate.
The Python interpreter, called IDLE, ready to accept code.
Hello World
Next to the three greater than signs (>>>), type: print
(Hello World), then press the ENTER key. Note that
the function print was displayed in purple, the string
(Hello World) was displayed in green, and that the
printed output is displayed in blue. Color-coded
indicators are a good way of knowing that something
was typed correctly as you go. Try typing a different
string inside the apostrophes and seeing the result,
like print(Python!). This is telling IDLE to show
whatever string
Note what happens when I forgot to add the
second apostrophe() to the string Hello World.
The interpreter takes the second apostrophe as the
end of the statement, and without it, an error
message will be returned. A SyntaxError occurs
when something was typed incorrectly in the code
(as opposed to compiling incorrectly, which is
beyond the scope of this tutorial). The incorrect
section was highlighted in red and the reasoning is
written in red. Should you make a mistake, simply
try again on the next line.
Simple Math
A simple math problem is a good way to
introduce the concept of variables:
A variable in programming, much like math, is
a way to store a value in memory for later use.
Variables are the backbone of programming.
Here is a few ways they are used:
To store user input in a place that can be used
later (in a function, perhaps)
To store the result of functions and loops, for
use in other functions and loops.
To allow the values in program to change
dynamically (while the program is running)
The math problem on the right stores the values
of a and b, and then uses these values to
designate the value of z (the third line means z
equals a divided by b)
Operators
Basic operators in Python are the same as they
are in mathematics:
+ (add)
- (subtract)
* (multiply)
/ (divide)
Python uses PEMDAS in the absence of
distinguishing parenthesis. For example:
7 + 8 * 4 is seen as 7 + (8 *4) not (7+8) * 4, because
multiplication is first in order of operations.
The examples on the right shows three slightly
more complicated operators:
The modulus operator (%), which takes the value of the
number on the left, divides it by the number on the right,
and returns the remainder.
The exponent operator (**) means, to the power of, so
2 to the second power is written: 2**2
The floor division operator(//) is the same as division,
except it rounds the result down to the nearest whole
number.
Translations:
1) X is equal to the remainder
of 100/24. Since 24 * 4 =
96. The remainder is 4.
2) Y is equal to 8 to the 2
nd
power. 8 * 8 = 64.
3) Z is equal to 99 divided by
21, rounded down to the
nearest whole number. 99
/ 21 = 4.714, which is
rounded down to 4.
4) For good measure, the
storage of the values is
shown with the variable A,
which uses the results of
the equations. A = (4) +
(64) + (4), or A =72.
The IF statement
The if statement is a conditional statement. It is
where the previous concepts are applied to the
creation of logic within a program.
A statement is a command given to a program
to execute what comes afterward, so the
program knows when it reads the word if that
a condition is to follow.
The breakdown of an if statement is as follows:
If (certain conditions are true):
then (execute this code)
Note that there is a double equal (==) operator
qualifying the statement. The double equal is
used in place of a singular equal sign to
differentiate between a comparison (n==1) and a
declaration (n=1).
Translation:
1) The variable N is equal to 40.
2) The if statement asks if the variable N is equal to 40
(which is true). Note the colon (:) that follows the
condition.
3) The print command will execute only if the statement
which precedes it is true. Since n is indeed equal to 40,
the condition is satisfied and the print function
executes.
4) Try the same statement with values that do not match,
like setting (n=40) and then having the if statement read
(if n ==44: ). Notice that nothing happens.
Else IF and Else
The Else IF and Else statements are extensions of the IF
statement, which gives the program more decisions to make in
a function. This method is used when there are two or more
conditions that need to be satisfied.
The breakdown of an IF-ElseIF-ELSE statement is as follows:
If (certain conditions are true):
then (execute this code)
Else, if (this condition is true, but the previous conditions arent)
then (execute this code instead)
Else (assume that neither of the previous conditions are true)
And (execute this code instead)
IMPORTANT: When the elif and else statements cannot
be indented in the interpreter. If pressing return
automatically indents the new line, press backspace and it
should appear as it does on the right.
Note in the example on the right that the greater than or
equal to sign (>=) is introduced as an operator. It, along
with less-than-or-equal-to (<=), are used to compare
values, which can be used to sort them from high-to-low
and vice versa.
Translation:
1) Y is set to 28
2) The first IF condition tests if Y is greater than or equal to 29 (since
Y=28, this is false)
3) The ELSE IF (written as elif in Python) tests if Y is equal to 28 (which
is true)
4) The ELSE tests every other condition. Since every number great than
and equal to 28 was tested by the first two conditions, the only
condition that remains is less than or equal to 27 (since Y = 28, this
is false)
5) Since the second statement is true, the display prints the code that
should be executed. Try this same block with different values for y
and see if you get the answer you expected.
Functions
Functions are a means of separating code
utilizing statements that apply to different
processes over and over without retyping
them.
Functions use the keyword def to indicate
that a function is to follow. The name of a
functions does not contain spaces, and
should be unique within your program:
def functionName():
Above, functionName is where you place
the name of the function you are creating.
The parenthesis () next to the function
name is for passing arguments, which will
be covered in the next chapter
NOTE: For this slide and the next, you want
to leave the IDLE interpreter and use the
IDLE editor. From the file menu, select File,
then select New File. Note that the window
is now blank, and it should look like a blank
text editor.
Translation:
1) The rear window is the IDLE editor (note the
absence of text at the top). Here I defined my
function with the keyword def, named it
myfunction(), and defined what should
happen when the function is called, which is
to print Testing my Function.
2) In the next part, I called the function I just
created in order to display what it does, but
typing it by name with blank parenthesis next
to it, like so: myfunction()
3) To test the function created in the IDLE editor,
select Run from the file menu, then select
Run Module, or simply press F5 (You will need
to save the file; it doesnt matter where or
what its called as long as the extension (.py or
.pyw) isnt changed.
4) An IDLE interpreter window (bottom window)
will open, showing you the results. I created a
function, told the interpreter that it should
print something when the function is called,
then I called the function.
Arguments
Arguments are a way to pass
values between functions. This is
the purpose of the parenthesis ()
next to a function declaration. It
is left blank if there are no
arguments to be passed.
Using arguments in functions are
useful when you want to calculate
a set of variables with one
function, then calculate the same
variables a different way in
another.
Remember to place a colon (:)
after the function definition to
avoid an error.
Translation:
1) Using the same function from the
previous slide, I entered the variables a
and b as arguments.
2) The code on the next line tells the
interpreter to print the result of adding
a+b.
3) The function was then called with the
values 45 and 55 as arguments. The
compiler automatically replaces the
variables a and b with the values
provided. These values are then
inserted into the functions expression,
which becomes: print(45+55).
4) After running the program (pressing F5),
the interpreter opens (bottom window)
and displays the correct result (100)
For Loops
A loop in programming is a way of telling the
program to execute code. For example, if you had
a group of people at a party and you wanted to
make sure they all got plates, you would say for
every person at the party, hand out one plate.
This a simplification of the process, but it
expresses the same concept.
The example on the right also introduces the
range function. As it sounds, the function returns
the range between a given set of items. The
range function can be use in many ways other
than the range(start, stop) shown here. Notice
that the 6 is not counted.
Translation:
1) The loop reads: for every number n from
one to six, print n.
2) The loop will pass continue to execute
print(n) until it reaches the designated
limit. Try inserting different numbers into
the range to understand how incremental
counting works.
While Loop
WHILE loops are similar to FOR loops, in that both
provide a method for repeating code until conditions
are met. The difference between the types is that a FOR
loop will execute a designated amount of time, whereas
a WHILE loops executes until certain conditions are met
(make a while loop similar to an if statement that
repeats).
This example introduces the incremental operator
called add AND, which is written as +=. It means
increase the value on the left by the increment on the
right. In a loop, the value will continue to climb at the
rate of the value on the right.
Translation:
1) The value of x is set at 0.
2) The loop reads, as long as x is less than 5, print out the
value of x
3) The add AND operator (+=) tells the loop to add 1 on each
increment, so x starts at 0, then becomes 1, then 2, and so
forth, each time the loop occurs until it reaches 5 and stops.
4) The output stops when it reaches five and does not fire the
print function because it is after the conditional statement.
If you would want the loop to stop on 5, then you would set
the limit to 6.
Strings
A string, or string literal, is a type of variable that
indicates the value is to be treated like a literal word. It
is notated by quotation marks , and should show up in
the editor/interpreter in green.
Strings are useful for storing text in a program, which
can be used later in a number of ways, including:
Taking entered text, like a name, and assigning it to a
variable.
Checking to see if entered text matches a string value
already in a program, like a user password.
Displaying text when a certain action is performed in the
code, such as an error prompt.
In the example on the right, the first string
variable is designated (Ninja), then a second is
created ( Art)note the space before Art
shows up in the printed resultand these two
strings are combined in the print function.
Lists
Lists are the Python equivalent of what arrays are
in many other languages. They are declared like
variables, but allow the programmer to store
multiple values inside of one variable. These
variables have indexes, which can be used to
find data inside of the structure.
The syntax for a basic list is as follows:
listName = [x, y, z, and so on]
As mentioned, the values for x, y, z are stored at
an index, which begins at 0 and counts upward,
so x is stored at index 0, y at index 1, z at index 2,
and so on.
The example on the right uses the FOR loop to
cycle through the indexes, just as it would a set of
numbers in a given range.
Tuples
Tuples are identical to lists, with one important
distinction: a tuple cannot be changed once it is
declared. This may seem an arbitrary difference
since you, the programmer, can simply make a list
and not change it. However, a tuple is designed to
prevent errors and bugs from altering sensitive data.
You may use a tuple to store constants (values that
arent subject to change like variables). For example,
you may want to store values that arent subject to
change (like sales tax, or vacation accrual rate) and
keep them separate from values that do (like sale
price or hours worked)
Note that a tuple uses parenthesis ( ) in its
declaration instead of brackets [ ], and that the
interpreter produced an error message when I tried
to change a value using the append function.
Translation:
1) For warriorList, I was able to use the append function to add
Rogue to the end of the three I already had (I could have
replaced an item by specifying the index, but since I didnt it
placed it at the end)
2) For warriorTuple, an error message was returned because the
program rejected my attempt to change a tuple (telling me the
tuple object has no such function.