In this exercise, you will work through some simple blocks of code so you learn the essentials of the Python language syntax.
For each of the code blocks below, read the code before running it. Try to imagine what it will do. Then run it, and check to see if you were right. If it did something other than what you expected, play with it a little bit. Can you make it do what you were expecting? Try changing it, and run it again, and see what happens.
Pressing Shift+Enter
will run the currently highlighted code block.
Feel free to create a new, empty code block and use it as a place to experiment with code of your own.
Let's start off with some simple math.
In [ ]:
1 + 1
In [ ]:
2 * 4
In [ ]:
(2 * 4) - 2
In [ ]:
4 ** 2 # Raise a number to a power
In [ ]:
16 / 4
In [ ]:
15 / 4
In [ ]:
2.5 * 2.0
In [ ]:
15.0 / 4
Next, let's move on to strings.
In [ ]:
'a' + 'b'
In [ ]:
'Python ' + 'is' + ' fun'
In [ ]:
"Python isn't afraid of single quotes"
In [ ]:
'It is not "afraid" of double quotes either'
In [ ]:
"The value is " + 17
In [ ]:
"The value is " + str(17)
In [ ]:
'The value is {0}'.format(17)
In [ ]:
'Is {0} smaller than {1}?'.format(5.0, 12)
In [ ]:
'Yes {1} is bigger than {0}.'.format(5.0, 12)
Let's look at logical values
In [ ]:
True
In [ ]:
True or False
In [ ]:
True and False
In [ ]:
1 < 2
In [ ]:
'a' > 'z'
In [ ]:
'a' = 'a'
In [ ]:
'a' == 'a'
Next, let's look at some lists.
In [ ]:
[1, 2, 3]
In [ ]:
range(1, 7)
In [ ]:
[1, 2] + [3]
In [ ]:
['a', 'b', 'c'] + ['c', 'd', 'e']
In [ ]:
1 in [1, 2, 3]
In [ ]:
7 in [1, 2, 3]
In [ ]:
len([1, 2, 3, 4, 5, 10, 20])
In [ ]:
max([1, 5, 2, 100, 75, 3])
Variables will hold onto values you give them.
In [ ]:
a = 3
print a
In [ ]:
a = 2
a
In [ ]:
a = 7
a + 1
In [ ]:
b = 2
a * b
In [ ]:
c = 'Python'
c
In [ ]:
d = c + ' is cool'
d
In [ ]:
a = [1, 2, 3]
a.extend([8, 10, 12])
a
In [ ]:
a[0]
In [ ]:
a[1]
In [ ]:
a[-1]
In [ ]:
a[-2]
In [ ]:
a[2:5]
In [ ]:
a = 5
b = 10
if a < b:
print "Smaller"
else:
print "Larger"
In [ ]:
a = 500
b = 100
if a < b:
print "Smaller"
else:
print "Larger"
In [ ]:
a = 10
b = 100
if a == b:
print "Same"
else:
print "Different"
In [ ]:
a = 10
b = 100
if a != b:
print "Not equal"
else:
print "Same"
In [ ]:
a = [1, 2, 3, 4, 5, 6]
for i in a:
print i
In [ ]:
for i in range(0, 20, 2):
print i
In [ ]:
a = 5
while a > 0:
print a
a = a - 1