A Beginner’s Guide to Python Programming

Embed Size (px)

Citation preview

  • 8/12/2019 A Beginners Guide to Python Programming

    1/15

    A Beginners Guide to Pyth

    Python Version: 3.3.4

  • 8/12/2019 A Beginners Guide to Python Programming

    2/15

    Contents

    For Starters (IDLE)

    Hello World!

    Variables Operators

    The IF statement

    ElseIF and Else

    Functions

    Arguments For Loop

    While Loop

    Strings

    Lists

    Tuples

  • 8/12/2019 A Beginners Guide to Python Programming

    3/15

    For Starters Python IDLE (shown right)

    On installation, IDLE (Python GUI) should be found in your startmenu 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 andsaved as a .py file, but for the sake of this tutorial,we will be using the interpreter to cover the pythonsyntax(the way it is written) and other basicprogramming concepts.

    Note that the interpreter functions like a commandprompt in Windows. You cannot delete items once

    the ENTER key is pressed. Mistakes should be of noconcern, howeverif an error occurs simply tryagain on the next line until you get the desiredoutput, or restart IDLE if youd like to work from aclean slate.

    The Python interpreter, called IDLE, ready

  • 8/12/2019 A Beginners Guide to Python Programming

    4/15

    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 forgo

    second apostrophe() to the strin

    The interpreter takes the second

    end of the statement, and withou

    message will be returned. A Syn

    when something was typed inco

    (as opposed to compiling incorre

    beyond the scope of this tutorial

    section was highlighted in red an

    written in red. Should you make

    try again on the next line.

  • 8/12/2019 A Beginners Guide to Python Programming

    5/15

    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 changedynamically (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 ofz (the third line means z

    equals a divided by b)

  • 8/12/2019 A Beginners Guide to Python Programming

    6/15

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

    Translati

    1) X is e

    of 10

    96. T

    2) Y is e

    powe3) Z is e

    21, ro

    near

    / 21

    roun

    4) For g

    stora

    showwhic

    the e

    (64)

    Th IF

  • 8/12/2019 A Beginners Guide to Python Programming

    7/15

    The IF statement The if statement is a conditionalstatement. It is

    where the previous concepts are applied to the

    creation of logic within a program.

    A statementis 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 varia

    (which is true). Note the colon (

    condition.

    3) The print command will executewhich precedes it is true. Since n

    the condition is satisfied and the

    executes.

    4) Try the same statement with valu

    like setting (n=40) and then havin

    (if n ==44: ). Notice that nothing

    El IF d El

  • 8/12/2019 A Beginners Guide to Python Programming

    8/15

    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 thegreater than or

    equal to sign (>=) is introduced as an operator. It, along

    with less-than-or-equal-to (

  • 8/12/2019 A Beginners Guide to Python Programming

    9/15

    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

    absence of text at t

    function with the k

    myfunction(), and d

    happen when the f

    to print Testing my

    2) In the next part, I c

    created in order to

    typing it by name w

    to it, like so: myfun

    3) To test the function

    select Run from the

    Run Module, or sim

    to save the file; it d

    what its called as l.pyw) isnt changed

    4) An IDLE interpreter

    will open, showing

    function, told the in

    print something wh

    then I called the fu

    A t

  • 8/12/2019 A Beginners Guide to Python Programming

    10/15

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

    Remember to place a colon (:)

    after the function definition to

    avoid an error.

    Translation:

    1) Using the same f

    previous slide, I e

    and b as argume

    2) The code on the

    interpreter to pra+b.

    3) The function was

    values 45 and 55

    compiler automa

    variables a and b

    provided. These

    inserted into the

    which becomes:4) After running the

    the interpreter o

    and displays the

    F

    L

  • 8/12/2019 A Beginners Guide to Python Programming

    11/15

    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 forevery 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. Therange 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 none to six, print n.

    2) The loop will pass continue

    print(n) until it reaches the

    limit. Try inserting differen

    the range to understand ho

    counting works.

    While Loop

  • 8/12/2019 A Beginners Guide to Python Programming

    12/15

    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 therate of the value on the right.

    Translation:

    1) The value ofx is set at 0.

    2) The loop reads, as long as x is lesvalue of x

    3) The add AND operator (+=) tells

    increment, so x starts at 0, then

    forth, each time the loop occurs

    4) The output stops when it reache

    print function because it is after

    If you would want the loop to sto

    the limit to 6.

    Strings

  • 8/12/2019 A Beginners Guide to Python Programming

    13/15

    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, whichcan 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

  • 8/12/2019 A Beginners Guide to Python Programming

    14/15

    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

  • 8/12/2019 A Beginners Guide to Python Programming

    15/15

    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 toprevent 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 ap

    Rogue to the end of the three I alread

    replaced an item by specifying the inde

    placed it at the end)

    2) For warriorTuple, an error message wa

    program rejected my attempt to chang

    tuple object has no such function.