CT320

CT320: Network and System Administration

Fall 2015

Python

See this page as a slide show

Python Overview

adapted from https://docs.python.org/3.4/tutorial/

Version

There were incompatible changes between Python 2 and Python 3. Treat Python 2 and Python 3 as similar, but distinct, languages.

This tutorial will discuss Python 3. Specifically, Python 3.4, because that’s the latest version available on the CSU lab machines as of this writing (October 2015).

Invoking Python

For backward compatibility, the default is Python 2. Therefore, you have to execute python3 to get Python 3.

    % python -V
    Python 2.7.8

    % python2 -V
    Python 2.7.8

    % python3 -V
    Python 3.4.1

    % ls -l /usr/bin/python
    lrwxrwxrwx 1 root root 7 Jul  5 08:16 /usr/bin/python -> python2

Help

The pydoc3 program tells you about functions:

    % pydoc3 abs
    Help on built-in function abs in module __builtin__:

    abs(...)
        abs(number) -> number

        Return the absolute value of the argument.

Help

pydoc3 can also tell you about control flow:

    % pydoc3 for

    The ``for`` statement
    *********************

    The ``for`` statement is used to iterate over the elements of a
    sequence (such as a string, tuple or list) or other iterable object:

       for_stmt ::= "for" target_list "in" expression_list ":" suite
                    ["else" ":" suite]

    ...

Interpretive mode

python3, with no arguments, starts in a “calculator” mode:

    % python3 -q
    >>> 2+2
    4
    >>> a=10
    >>> from math import sqrt
    >>> sqrt(a)
    3.1622776601683795
    >>> control-D to exit
    % 

The previous lines can be edited using the arrow keys.

One-liner

To execute a single line of Python, use -c:

    % python3 -c 'v=355/113; print(v)'
    3.1415929203539825

Script

A Python script starts with #! /usr/bin/python3:

    % cat hi
    #! /usr/bin/python3
    print("Hello, world!")
    % ./hi
    Hello, world!
    % 

Data Type Overview

NameExamplesNotes
BooleanTrue, Falsecapitalized
Number1, 3.4, 4.5e8, 2**1000big big big
String"Don't" 'believe' r'every\thing' """you   
read!"""
immutable
List[1,2.3,"fruit",[45,5]]mutable
Tuple(23, "skidoo")immutable
Set{1,2,3}mutable
Dictionary{"Jack":"CT320", "Chris":"CS160"}mutable

Variables

    # Note lack of typing
    val=42
    val="hello there folks"
    Δ=[val, 42]

Indentation Determines Block Structure

Note the colon and lack of braces and then/fi

    if a>100:
        print("Holy Toledo, a is too big at", a)
        a=100
    b=a

Tabs are interpreted as every eight character positions. Changing the tab stops in your editor will not alter how Python interprets tab characters.

Wise Pythoners have their editor expand tabs to spaces, which avoids the whole problem.

if

    if age<18:
        print("You’re a punk")
    elif age>=65:
        print("You’re a geezer")
    elif age==58:
        print("You’re the ideal age")
    else:
        print("Whatever.")

This is as close as we get to a switch statement.

while

    while a>=0:
        print(a, end=" ")
        a-=1                    # No ++ or --
    print("Blastoff!")

for

The for loop iterates over a list:

    for p in [2,3,5,7,11,13,17,19]:
        print(p)

Or anything else that’s iterable:

    sum=0
    for n in range(100):
        sum+=n
    print("The sum of 0..99 is", sum)

Though a real Pythoner will do this:

    print("The sum of 0..99 is", sum(range(100)))

Sorry, C fans: no C-style for loop.

break/continue/pass

for/else

    for n in range(2, 100):
        for x in range(2, n):
            if n % x == 0:
                print(n, 'equals', x, '*', n/x)
                break
        else:
            # loop fell through without finding a factor
            print(n, 'is a prime number')

The indentation is correct: the else is associated with the inner for, not the if! The else clause is executed if the for loop ended “normally”, not via break.

Functions

    def factorial(n):
        if n<=1:
            return n
        else:
            return n*factorial(n-1)

Also:

Scope

Ignoring modules, there are only two scopes: global and function local.

Variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

Boolean Operators

Boolean operators: and, or, not

and and or are short-circuiting, and return the last value evaluated.

Sorry, C fans: no &&, ||

Arithmetic Operators

Sorry, C fans: no ++ or --

String Operators

List Operators

Tuple Operators

Set Operations

Dictionary Operations

Sequence Operators

Strings, lists, tuples, and sets are all sequences, with many methods.

Primes

    max = 100

    s = set(range(2,max))

    for candidate in range(2,max):
        s -= set(range(candidate*2, max, candidate))

    print(s)

Reference Semantics

A variable holds a reference to an object. This code:

    a=[1,2,3,4,5]
    b=a
    a[2] = 33
    print(a)
    print(b)

Produces this:

    [1, 2, 33, 4, 5]
    [1, 2, 33, 4, 5]

To make a copy, use b=a[:] or b=a.copy().

List Comprehensions

Long way:

    squares = []
    for x in range(10):
        squares.append(x**2)

Short way:

    squares = [x**2 for x in range(10)] 

Multiple for loops and if statements are allowed.

Output

print(value, …, sep=' ', end='\n', file=sys.stdout, flush=False)

Prints values, separated by sep, with end after all values, to file, with optional flushing.

File I/O

Show nameserver lines in /etc/resolv.conf:

    f = open('/etc/resolv.conf', 'r')
    for line in f:
        if "nameserver" in line:
            print(line, end='')
    f.close()

or:

    with open('/etc/resolv.conf', 'r') as f:
        for line in f:
            if "nameserver" in line:
                print(line, end='')

File object methods

Not appearing in this lecture

Modified: 2015-11-03T13:44

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building