Python Tutorial: dir, Data Types, Strings, and Exceptions
Advertisement
This Python programming tutorial covers the dir function, data types, strings, and exception handling.
Pass Statement
Sometimes you need to specify an empty block of code:
if name in namelist:
# Not implemented yet (or nothing)
pass
else:
statements
pass is a “no-op” statement. It does nothing but serves as a placeholder.
Long Lines
Sometimes you’ll have long statements that you want to break across multiple lines. Use the line continuation character (\):
if product=="game" and type=="pirate memory" \
and age >= 4 and age <= 8:
print "I'll take it!"
However, this is not needed for code within (), [], or {}.
Basic Datatypes
Python has a few primitive data types:
- Numbers
- Strings (character text)
Numbers
Python has 5 types of numbers:
- Booleans
- Integers
- Long Integers
- Floating-point numbers
- Complex (imaginary numbers)
Booleans (bool)
Two values: True, False
a = True
b = False
Evaluated as integers with values 1, 0:
c = 4 + True # c = 5
d = False
if d == 0:
print "d is False"
Integers (int)
Signed integers up to machine precision:
a = 37
b = -299392993
c = 0x7fa8 # Hexadecimal
d = 0253 # Octal
Typically 32 bits.
Long Integers (long)
Arbitrary precision integers:
a = 37L
b = -126477288399477266376467L
Integers that overflow promote to longs.
Integer Operations
| Operator | Description |
|---|---|
+ | Add |
- | Subtract |
* | Multiply |
/ | Divide |
// | Floor divide |
% | Modulo |
** | Power |
<< | Bit shift left |
>> | Bit shift right |
& | Bit-wise AND |
| | Bit-wise OR |
^ | Bit-wise XOR |
~ | Bit-wise NOT |
abs(x) | Absolute value |
pow(x,y[,z]) | Power with optional modulo ((x**y)%z) |
divmod(x,y) | Division with remainder |
Integer Division
- Classic division (
/) - truncates>>> 5/4 1 - Floor division (
//) - truncates (same)>>> 5/4 1 - Future division (
/) - Converts to float>>> from future import division >>> 5/4 1.25
If truncation is intended, use //.
Floating-Point Numbers
Use a decimal or exponential notation:
a = 37.45
b = 4e5
c = -1.345e-10
Represented as double precision using the native CPU representation (IEEE 754). This provides 17 digits of precision, with an exponent from -308 to 308. Be aware that floating-point numbers are inexact when representing decimal values.
>>> a = 3.4
>>> a
3.3999999999999999
This is due to the underlying floating-point hardware on the CPU, not just Python.
Floating-Point Operators
| Operator | Description |
|---|---|
+ | Add |
- | Subtract |
* | Multiply |
/ | Divide |
% | Modulo (remainder) |
** | Power |
pow(x,y[,z]) | Power with optional modulo (x**y)%z |
divmod(x,y) | Division with remainder |
Additional functions are available in the math module:
import math
a = math.sqrt(x)
b = math.sin(x)
c = math.cos(x)
d = math.tan(x)
e = math.log(x)
Converting Numbers
Type names can be used to convert:
a = int(x) # Convert x to integer
b = long(x) # Convert x to long
c = float(x) # Convert x to float
Example:
>>> a = 3.14159
>>> int(a)
3
Also works with strings containing numbers:
>>> a = "3.14159"
>>> float(a)
3.1415899999999999
>>> int("0xff",16) # Optional integer base
255
Strings
Written in programs with quotes:
a = "Yeah but no but yeah but..."
String Escape Codes
| Escape Code | Description |
|---|---|
\n | Line feed |
\r | Carriage return |
\t | Tab |
\xhh | Hexadecimal value |
\" | Literal quote |
\\ | Backslash |
Strings are an ordered sequence of bytes (characters). They are stored as 8-bit data (ASCII). Strings work like an array: s[n].
a = "Hello world"
Slicing/substrings: s[start:end]
d = a[:5] # d = "Hello"
Concatenation (+):
a = "Hello" + "World"
Length (len):
>>> s = "Hello world"
>>> len(s)
11
Membership test (in):
>>> 'e' in s
True
Replication (s*n):
>>> s = "Hello"
>>> s*5
'HelloHelloHelloHelloHello'
String Methods
Strings have “methods” that perform various operations with the string data.
-
Stripping any leading/trailing whitespace:
t = s.strip() -
Case conversion:
t = s.lower() t = s.upper() -
Replacing Text:
t = s.replace("Hello", "Hallo")
More String Methods
| Method | Description |
|---|---|
s.endswith(suffix) | Check if string ends with suffix |
s.find(t) | First occurrence of t in s |
s.index(t) | First occurrence of t in s |
s.isalpha() | Check if characters are alphabetic |
s.isdigit() | Check if characters are numeric |
s.islower() | Check if characters are lower-case |
s.isupper() | Check if characters are upper-case |
s.join(slist) | Joins lists using s as delimiter |
s.lower() | Convert to lower case |
s.replace(old,new) | Replace text |
s.rfind(t) | Search for t from end of string |
s.rindex(t) | Search for t from end of string |
s.split([delim]) | Split string into list of substrings |
s.startswith(prefix) | Check if string starts with prefix |
s.strip() | Strip leading/trailing space |
s.upper() | Convert to upper case |
String Mutability
Strings are “immutable” (read only). Once created, the value can’t be changed.
>>> s = "Hello World"
>>> s[1] = 'a'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>>
All operations and methods that manipulate string data always create new strings.
String Conversions
To convert any object to a string:
s = str(obj)
Produces the same text as print. Actually, print uses str() for output.
>>> x = 42
>>> str(x)
'42'
String Splitting
Strings often represent fields of data. To work with each field, split into a list:
>>> line = 'GOOG 100 490.10'
>>> fields = line.split()
>>> fields
['GOOG', '100', '490.10']
Lists
An array of arbitrary values:
names = [ "Elwood", "Jake", "Curtis" ]
nums = [ 39, 38, 42, 65, 111]
Can contain mixed data types:
items = [ "Elwood", 39, 1.5 ]
Adding new items (append, insert):
items.append("that") # Adds at end
items.insert(2,"this") # Inserts in middle
Concatenation: s + t
s = [1,2,3]
t = ['a','b']
s + t # --> [1,2,3,'a','b']
Lists are indexed by integers (starting at 0):
names = [ "Elwood", "Jake", "Curtis" ]
names[0] # "Elwood"
names[1] # "Jake"
names[2] # "Curtis"
Negative indices are from the end:
names[-1] # "Curtis"
Changing one of the items:
names[1] = "Joliet Jake"
More List Operations
Length (len):
>>> s = [ "Elwood", "Jake", "Curtis" ]
>>> len(s)
3
>>>
Membership test (in):
>>> 'Elwood' in s
True
>>> 'Britney' in s
False
>>>
Replication (s*n):
>>> s = [1,2,3]
>>> s*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>>
List removal:
# Removing an item
names.remove("Curtis")
# Deleting an item by index
del names[2]
File Input and Output
Opening a file:
f = open("foo.txt","r") # Open for reading
g = open("bar.txt","w") # Open for writing
To read data:
line = f.readline() # Read a line of text
data = f.read() # Read all data
To write text to a file:
g.write("some text")
To print to a file:
print >>g, "Your name is", name
Looping over a File (reading a file line by line):
f = open("foo.txt","r") # Open for reading
for line in f:
# Process the line
...
f.close()
Alternatively:
for line in open("foo.txt","r") :
# Process the line
...
This reads all lines until you reach the end of the file.
Type Conversion
In Python, you must be careful about converting data to an appropriate type:
x = '37' # Strings
y = '42'
z = x + y # z = '3742' (concatenation)
x = 37
y = 42
z = x + y # z = 79 (integer +)
This differs from Perl where "+" is assumed to be concatenation.
Simple Functions
Use functions for code you want to reuse:
def sumcount(n):
total = 0
while n > 0:
total += n
n -= 1
return total
Calling a function:
a = sumcount(100)
A function is a series of statements that perform some task and return a result.
Library Functions
Python comes with a large standard library. Library modules are accessed using import:
import math
x = math.sqrt(10)
import urllib
u = urllib.urlopen("https://www.python.org/index.html")
data = u.read()
Exception Handling
Errors are reported as exceptions. An exception causes the program to stop:
>>> f = open("file.dat","r")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'file.dat'
>>>
For debugging, the message describes what happened, where the error occurred, along with a traceback.
dir() Function
Useful for exploring and inspecting objects. dir(obj) returns all names defined in obj.
>>> import sys
>>> dir(sys)
dir() will also tell you what methods/attributes are available on an object.
>>> a = "Hello World"
>>> dir(a)
Advertisement