When starting with Python 2.7, two built-in functions are extremely helpful for quick learning: dir(module) lists all methods and attributes of a module, while help(module) provides detailed usage instructions for each method. Mastering these early accelerates the learning process for any new language.
Python strikes a great balance for general-purpose development when performance or platform constraints are not critical. It is widely adopted in fields like machine learning, especially in non-ARM deployement scenarios.
Most Ubuntu systems come with Python 2.7 pre-installed, so installation steps are skipped here. To run a script, use:
python hello.py
If permission issues arise, add execute permission with:
sudo chmod a+x hello.py
Reading user input from the command line is straightforward:
user_name = raw_input('please enter your name: ')
print 'hello,', user_name
Printing multiple strings concatenates them with spaces automatically:
print 'The quick brown fox', 'jumps over', 'the lazy dog'
# Output: The quick brown fox jumps over the lazy dog
For multi-line strings, Python supports triple-quoted syntax for better readability:
print '''line1
line2
line3'''
# Output:
# line1
# line2
# line3
Python is dynamically typed—variables can hold any data type and be reassigned to different types later.
When working with Chinese characters in source code, always declare UTF-8 encoding to avoid garbled output. Add these lines at the top of your script:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
The first line is ignored by Windows but tells Linux/macOS the file is a Python executable. The second line ensures the interpreter reads the code as UTF-8.
List Operations
Lists are mutable ordered collections. Common operations include:
students = ['Michael', 'Bob', 'Tracy']
students.append('Adam')
print students # ['Michael', 'Bob', 'Tracy', 'Adam']
students.insert(1, 'Jack')
print students # ['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']
students.pop()
print students # ['Michael', 'Jack', 'Bob', 'Tracy']
students.pop(1)
print students # ['Michael', 'Bob', 'Tracy']
Lists can contain mixed data types, including nested collections:
mixed_list = ['python', 'java', ['asp', 'php'], 'scheme']
print len(mixed_list) # 4
Tuples
Tuples are ordered collections similar to lists but immutable after initialization:
coordinates = (10, 20)
# coordinates[0] = 30 # This would raise an error
Conditional Statements
Python uses elif (short for else if) with strict indentation rules:
age = 3
if age >= 18:
print 'adult'
elif age >= 6:
print 'teenager'
else:
print 'kid'
Dictionaries (dict)
Dictionaries store key-value pairs for fast lookups. A key can only map to one value—latter assignments override earlier ones:
scores = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
print scores['Michael'] # 95
# Check if a key exists
print 'Thomas' in scores # False
Sets
Sets are unordered collections of unique keys (no values). They support mathematical operations like intersection and union:
number_set = set([1, 2, 3])
number_set.add(4)
number_set.remove(1)
set_a = set([1, 2, 3])
set_b = set([2, 3, 4])
print set_a & set_b # set([2, 3]) (intersection)
print set_a | set_b # set([1, 2, 3, 4]) (union)
Type Conversion
Python provides built-in functions for type casting:
print int('123') # 123
print int(12.34) # 12
print float('12.34') # 12.34
print str(1.23) # '1.23'
print bool(1) # True
print bool('') # False
Loop Examples
Separate even and odd numbers using a while loop:
#!/usr/bin/python
# coding: utf-8
nums = [12, 5, 8, 7, 3, 10]
evens = []
odds = []
while len(nums) > 0:
val = nums.pop()
if val % 2 == 0:
evens.append(val)
else:
odds.append(val)
print evens
print odds
Iterate over sequences with for loops:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
for char in 'Python':
print 'Current letter:', char
fruits = ['banana', 'apple', 'mango']
for fruit in fruits:
print 'Current fruit:', fruit
Traverse with index using range():
#!/usr/bin/python
# -*- coding: UTF-8 -*-
fruits = ['banana', 'apple', 'mango']
for idx in range(len(fruits)):
print 'Current fruit:', fruits[idx]
Check for primee numbers in a range:
#!/usr/bin/python
# coding: utf-8
for num in range(10, 20):
for i in range(2, num):
if num % i == 0:
quotient = num / i
print '%d equals %d * %d' % (num, i, quotient)
break
else:
print num, 'is a prime number'
Use break to exit loops early:
#!/usr/bin/python
# coding: utf-8
for char in 'python':
if char == 'h':
break
print 'Character:', char
counter = 10
while counter > 0:
print 'Current value:', counter
counter -= 1
if counter == 5:
break
print "Good bye"
Nested List Comprehensions
List comprehensions can be nested to transform data structures. For a 3x4 matrix:
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]
Transpose the matrix (swap rows and columns) with a nested comprehension:
transposed = [[row[i] for row in matrix] for i in range(4)]
print transposed # [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
This is equivalent to the explicit loop version:
transposed = []
for i in range(4):
new_row = []
for row in matrix:
new_row.append(row[i])
transposed.append(new_row)
print transposed # [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
For this use case, the built-in zip() function is more concise:
print list(zip(*matrix)) # [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]