Python Basics

Python is one of the most popular high-level programming languages. Its major features are:

Its major competition as a scripting language is Perl. Perl has a much longer learning curve and is notoriously disorganized, making it much harder to read, write and maintain, but it can do more things concisely, and has a much larger library of ready-to-use add-in modules. Perl’s text handling is also superior, mainly because regular expressions are built into the language, rather than being an add-in module. Even though Perl is also interpreted, it benchmarks about five times as fast as Python for pure text processing stuff.

Python Features

Data Types

Everything is an object —number, string, list, whatever. The fundamental object classes are:

The groups can be divided into mutable (lists and dictionaries) and immutable (strings and tuples). For instance, the sequence

myname = "John"
myname[2] = "a"
is an error, but
mylist = ["John", "R", "Dierdorf"]
mylist[1] = "Ralph"  #changes list in place
and
mydict["drinkcolor"] = "pink"
mydict["drug"] = "aspirin"  #adds a new item
are OK.

In Python, variables are not typed and do not need to be pre-declared. (They come into existence when something is first assigned to them.) Unlike Perl, variables do have to have been assigned a variable before use. For example:

a = 1            #a is created as type int
b = "something"  #created as type str
c = [1, 2, 3]    #created as type list
a = 3.14         #now a is a float
a = x            #error -- x is undefined
x = 0            #now x is defined
a = x            #now a is an int again

Functions

Python has four kinds of functions:

Statements

Python has pretty much the standard repertoire of statements: assignment (a = 5/2), tests (if), loops(for, while), console I/O (print, input), and so on. One thing that makes Python almost unique these days is that grouping of statements is done by indentation, not using {...} as is typical in most languages. For example:


age = float(input("How old are you? "))
if age < 21:
    print("Get out of this bar!")
else:
    drink = input("What would you like? ")
    print("Have some peanuts.")
    mix(drink)

#next statement goes here

Note that keyboard input is always a string, so the float() function was used to convert it to numeric. (If I had used int() for the conversion, then some smartass who answered “20.75” would have caused an error.) mix is presumably a user-defined function that expects a string argument.

In the same manner, there is no “end of statement” indicator; statements are ended by a carriage return.

Examples

Sum of Digits

Exam Average

Print String 10 Times

Error-Handling

One of the strong points of Python’s design is that one can write programs that are quite difficult to crash. I won’t get into the nasty details, but a typical use is:
try 
    myfile=file.open("/home/dierdorf/mystuff", r)
except
    print("No such file.")
    #possible code to correct the error
This is how to fix the SumOfDigits program so it won’t crash when it is not fed an integer:

...
try
    value = int(input("Enter a positive integer: "))
except
    value = 0
# check that value is positive
while value <= 0:
    try:
        value = int(input("Try again - enter positive integer: "))
    except:
        value = 0
...
If the conversion to int fails, then setting value to zero causes the program to emit the “Try again...” message and ask for another input. Note this has to be done for both input statements.

User-Defined Classes

The programmer can define new classes. This is called Object-Oriented Programming, or OOP for short. An object (a particular instance of a class) contains both data and the methods that can be used on the data. For example, it would be possible to define a class Employee, with data like name, salary, position, etc. If Susan is an object of class Employee, then her data could be accessed via methods like Susan.changesalary, Susan.lastname, and so on. Setting up classes takes a lot of work; the advantage is that classes can be inherited, so that one could then define class Manager as a subset of Employee, and all the existing data and methods would automatically be part of any new Manager object, along with any new stuff that had been defined as unique to managers.

Note that the way Python is defined, everything is an object, as I said, so "John", 12.75 and 47 are objects of class str, float and int, respectively, and they have methods that only work for such things. In theory, one could redefine class int so that "+" actually performed a multiply-and-then-add-one operation, so 5+7 would give 36.

Defining classes is far too complicated for an introduction like this, but keep it in the back of your head for someday when you get smart.


Last modified: Tue Feb 12 12:08:54 CST 2013