User Tools

Site Tools


user:bh011695:portfolio:pythontutorial

Python Programming Tutorial

A few things to get started. First and foremost, Python syntax is very picky. Make sure all the indentation is correct and colons are in their places. Those two things, I would say make up for almost all of my syntax errors. Make sure to have #!/usr/bin/python at the beginning of your code. If you're using Python for Windows, that line isn't necessary but otherwise, you will need it. To make your code executable, you're going to need the following line:

lab46:~$ chmod 711 file.py

This will give the user full read, write, and execute permissions but only execution for group and other.

Print statements are quite simple in python, almost too simple. One little command is all you need.

print "Hello, World!"

When using print statements in python, there is no need to enter a new line character to start a new line. New lines are entered automatically at the end of the print statement. If you don't want a new line when using multiple print statements, do something like the following:

print "Hello, World!",
print "Goodbye, World!"

This should give you the following output:

lab46:~$ ./hello.py
Hello, World! Goodbye, World!"

Getting Input From The User

To get some input from the keyboard, it's as easy as this.

myVar = raw_input("Enter some input: ")

There is also the input() function. However, this seems to only work with numeric values. So, if you're looking to enter a string stick with raw_input(). Here's a simple example of getting input and displaying it to the screen.

name = raw_input("What is your name? ")
print "Hello", name
lab46:~$ ./name.py
What is your name? John
Hello John

If Statements and Case Structures

Ifs

If you've done any C programming, if statements are exactly the same minus one thing. At the end of the if statement add a colon.

#!/usr/bin/python
var1 = 1
var2 = 3
 
if (var1 < var2):
   print var1, "<", var2

Running the program should result in the following output:

lab46:~$ ./if.py
1 < 3

Elses

Now if you wanted to make this an if then else the code would look like this:

#!/usr/bin/python
var1 = 3
var2 = 1
 
if (var1 < var2):
   print var1, "<", var2
else:
   print var2, ">", var1

Now the program's output should look like this:

lab46:~$ ./if.py
3 > 1

Else ifs

There are also the else ifs, which again, are not much different than doing them in C.

if (var1 < var2):
   print var1, "<", var2
elif (var1 > var2):
   print var1, ">", var2

As far as case structures are concerned, they don't exist as they do in C. In place of case structures, in python you would just use a bunch of if/elif statements.

if (var == 0):
   #do this
elif (var == 1):
   #do this
elif (var == 2):
   #do this

Loops

While Loops

A simple while loop would look something like this:

x = 0
X_MAX = 10
 
while (x < X_MAX):
   print x,
   x = x + 1
lab46:~$
0, 1, 2, 3, 4, 5, 6, 7, 8, 9

If you want each number on a different line, remove the comma from the print statement.

For Loops

For loops, in python, come in various shapes and sizes depending on what you're doing. In most cases, this one will be fine for whatever you're doing.

for x in range(0, 10):
  print x,

This should give you the same output as the above while loop.

Functions

Functions in python consist of the function heading, the function body, and the return statement. Just like with variables, there's no need to declare a data type with functions. Below is some simple code for a function that adds a few numbers together. The first line is your function heading and the second line is your return statement.

 def sum(a, b, c):
    return a + b + c

If you wanted to have a body to this function, it could also be done like this.

 def sum(a, b, c):
    d = a + b + c
    return d

Classes and Objects

If you've done problem solving or C++, classes in python may seem a bit odd. Unlike in C++, in Python there are no such things as private class members. Everything in a python class is a public member. Let's create a class called circle.

#!/usr/bin/python
 
class circle:
  def __init__(self, radius):
    self.diameter = radius * 2
    self.circumference = self.diameter * 3.14
    self.area = 3.14 * radius * radius
 
myCircle = circle(25.0)
print "Diameter:", myCircle.diameter
print "Circumference:", myCircle.circumference
print "Area:", myCircle.area

When you run this you should get the following output.

@lab46:~/python/pythonTut$ ./circle.py 
Diameter: 50.0
Circumference: 157.0
Area: 1962.5

Think of the __init__() function as your constructor to initialize your class variables. Always remember to include self, the object itself, in this function. If not, you'll see some fairly nasty syntax errors. However, when you initialize the object, there's no need to include a value for self as you can see in “myCircle = circle(25)”. When you use the variable members make sure to use the following syntax: objectName.variableName or in the case of a class function objectName.classFunc().

Another way to do this would be to not access your variables directly a la C++ and return values for diameter and circumference.

#!/usr/bin/python
 
class circle:
  def __init__(self, radius):
    self.radius = radius
 
  def getRadius(self):
    return self.radius
 
  def calcDiameter(self):
    return self.radius * 2
 
  def calcCircumference(self):
    return 2 * 3.14 * self.radius
 
  def calcArea(self):
    return 3.14 * radius * radius
 
myCircle = circle(25.0)
print myCircle.getRadius()
print myCircle.calcDiameter()
print myCircle.calcCircumference()

When you run this you should get the following output.

@lab46:~/python/pythonTut$ ./circle.py 
Radius: 25.0
Diameter: 50.0
Circumference: 157.0
Area: 1962.5

A few things to remember when doing it this way. First, when you define your functions, all of them require the parameter “self”. This really has no special meaning, but is a convention python has for readability. The other thing I'd like to mention is that I specifically made the radius parameter in the declaration a floating point value. In python, data types are created by whatever you store in the variable. When I returned the circumference value and multiplied the radius by 3.14, even if I had used an integer value of simply 25, it would have come out as 157.0 because of 3.14 being a floating point value. However, the rest of the return values would have been integers. I'll touch on some ways to deal with this later on.

Inheritance

Time for some inheritance. Inheritance can be fairly confusing in python. There's nothing new with the parent class. In the child class Person, we have a few new lines, though. Person.init(self, last, first) makes a call to the constructor of the parent class so that all of the parent's attributes get set when the constructor to the employee class is called. Anytime we make a call to a parent class, it will look similar to this. If you only wanted to print the name of the Employee it would look like this. Person.printName(self). Other than that, the only new thing is the use of the format specifier. print “Gross Pay:”, '%.2f' % self.grossPay. This line simply formats the grossPay variable to 2 decimal places. The %.2f could be a %.3f for 3 places and so on.

#!/usr/bin/python
 
class Person:
    def __init__(self, last, first):
        self.lastName = last
        self.firstName = first
 
    def printName(self):
        print "Name:", self.lastName, self.firstName
 
class Employee(Person):
    def __init__(self, last, first, ID, rate, hours):
        Person.__init__(self, last, first)
        self.ID = ID
        self.hourlyRate = rate
        self.hoursWorked = hours
        self.grossPay = self.hourlyRate * self.hoursWorked
 
    def printEmployeeInfo(self):
        print "ID:", self.ID
        Person.printName(self)
        print "Rate:", self.hourlyRate
        print "Hours Worked:", self.hoursWorked
        print "Gross Pay:", '%.2f' % self.grossPay                                        
 
brad = Employee("Hammond", "Brad", 9876, 8.25, 32.25)
brad.printEmployeeInfo()

Composition

Ahhh, composition, a class that contains and object from another class. In this case we'll use name and person. Composition is a “has a ” relationship. Every person has a name.

#!/usr/bin/python
 
class Name:
  def __init__(self, first, last):
    self.first = first
    self.last = last
 
  def getFirst(self):
    return self.first
 
   def getLast(self):
     return self.last
 
class Person:
  def __init__(self, first, last, age):
    self.n = Name(first, last)
    self.age = age
 
  def getFirstName(self):
    return self.n.getFirst()
 
  def getLastName(self):
    return self.n.getLast()
 
  def getAge(self):
    return self.age
 
brad = Person("Brad", "Hammond", 26)
print "Name:", brad.getFirstName(), brad.getLastName()
print "Age:", brad.getAge()

Most of this code should look fairly familiar. We create a class called Name that consists of a first name and a last name and methods to return the first name and last name. Immediately afterwards, we create a new class called Person which has an object created in its constructor called self.n to store a name. An object of type Person contains a first and last name and an age. The Person class contains methods to return the first name, last name, and the age. Getting the first name and last name involves calling the get methods in the Name class. When you run the code it should give you the following output.

lab46:~ ./composition
Name: Brad Hammond
Age: 26

Private Class Members

It is also possible to create private data members within your classes using a certain naming convention. Normally a class member would look something like the following:

self.name = arg1

To create a private member it would look like this:

self.__name = arg1

From this point direct access to self.__name is impossible

brad@dhcp-181:/media/06F6-9DC2/Notepad++/python$ python privateMember.py 
Printing via function myClass.printStuff() Brad
None
Printing via direct access
Traceback (most recent call last):
  File "privateMember.py", line 11, in <module>
    print "Printing via direct access", self.__name, "\n"
NameError: name 'self' is not defined

Predefined Functions

Python has a lot of really usefully built in functions used for various purposes. In most cases, they're just there. You don't have to do any includes like in C/C++. However, some things do require an import, python's version of C/C++'s include.

Math Functions

abs()

abs() returns the absolute value of its parameter. These can be integers, floating point values, or even complex numbers. If the parameter is a complex number the function returns the number's magnitude.

abs(num)

complex()

complex() converts its parameters to a complex number. Its parameters can be integers, floating point values, and the 2nd parameter may be imaginary. So it may take the following forms:

complex(num)
complex(num1, num2)

pow()

pow() comes in two forms. Form one is:

pow(x, y)

Form two is:

pow(x, y, z)

In form one, we simply raise x to the power y. The 2nd form is equivalent to (x ^ y) % z.

round()

round() is a bit screwy. It takes one or two arguments in the form of round(x, y). It rounds x to y decimal places. If y is not specified, it treats y as if you had entered a zero

round(x, y)
round(x)

Data Type Conversion

bin()

bin() takes an integer value and converts it into a binary number

bin(25)

bool()

bool() converts a number into a bool value of true or false. A zero evaluates to false, anything other than zero evaluates to true.

bool(1)

float()

float() converts a number into a floating point value. Entering 25 as a parameter will return 25.0.

float(25)

hex()

hex() converts an integer into a hexadecimal value. hex(632) returns 0x278

hex(632)

long()

long() converts an integer into a long integer value.

long(83)

oct()

oct() converts an integer number into an octal value.

oct(25)

This returns 031.

Brad Hammond

user/bh011695/portfolio/pythontutorial.txt · Last modified: 2012/02/23 20:28 by bh011695