In [1]:
for number in [0, 1, 2, 3, 4, 5, 6]:
if number % 2 == 0:
print "Even number:", number
What do we see?
In [2]:
(50 - 5.0 * 6) / 4
Out[2]:
**
operator can be used to calculate powers
In [3]:
5 ** 2
Out[3]:
Enclosed in single quotes '...'
or double quotes "..."
.
\
can be used to escape characters
In [4]:
"I can eat glass it doesn't hurt me"
Out[4]:
In [5]:
'I can eat glass it doesn\'t hurt me'
Out[5]:
print
statement.\
to be interpreted as special characters, you can use raw strings by adding an r before the first quote
In [6]:
print 'I can eat glass.\nIt doesn\'t hurt me'
print '---------------'
print r'I can eat glass.\n It doesn\'t hurt me'
"""..."""
or '''...'''
In [7]:
print '''I can eat glass
It doesn't hurt me'''
+
*
In [8]:
print 'AA' + 'BB'
print 'AA' * 3
In [9]:
word = 'python'
print word[0]
print word[-1]
print word[-2]
In [10]:
# Get characters from position 1 to position 4 (4 characters)
print word[1:5] # exclude 5
# Get characters from position 1 to the end
print word[1:]
# Get all characters except the final character
print word[:-1]
# Get 3 last characters
print word[-3:]
In [11]:
# get error when trying to change
word[0] = 'J'
In [12]:
print 'J' + word[1:]
len()
function can be used to calculate length of string
In [13]:
print len(word)
In [14]:
squares = [1, 4, 9, 16, 25]
print squares
In [15]:
print squares[0] # Indexing returns the item
In [16]:
print squares[-1]
In [17]:
print squares[-3:] # Slicing returns a new list
In [18]:
cubes = [1, 8, 27, 65, 125] # something's wrong here
print cubes
In [19]:
cubes[3] = 64
print cubes
+
operatorappend()
methodlen()
function
In [20]:
print squares + [36, 49]
In [21]:
squares.append(36)
print squares
In [22]:
print len(squares)
In [2]:
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print letters
In [3]:
letters[2:5] = ['C', 'D', 'E']
print letters
In [4]:
letters[2:5] = ['-']
print letters
In [37]:
a, b, c = [1, 2, 3]
print a, b, c
In [36]:
a, b, c = [1, 2]
In [39]:
a, b = 1, 2
a, b = b, a
print a, b