%install_ext https://raw.github.com/minrk/ipython_extensions/master/nbtoc.py
%load_ext nbtoc
%nbtoc
Installed nbtoc.py. To use it, type: %load_ext nbtoc The nbtoc extension is already loaded. To reload it, use: %reload_ext nbtoc
6 + 7.5
13.5
type("cows")
str
n = 22
n
22
beasts = "cows"
True
True
False
False
4 > 10
False
"True" == True
False
score1 = 4
score2 = 10
if score1 > score2:
print "We're #1!"
elif score2 > score1:
print "Better luck next time"
else:
print "It's not over!"
Better luck next time
def eval_scores(score1, score2):
if score1 > score2:
print "We're #1!"
elif score2 > score1:
print "Better luck next time"
else:
print "It's not over!"
eval_scores(40, 30)
We're #1!
def very(adj):
return 'totally ' + adj
very('fun')
'totally fun'
difficulty = very('hard')
difficulty
'totally hard'
Conveniently handle bunches of data that will all need to be treated together!
names = ['Linda', 'Katina', 'Alexandria', 'Jennifer']
names
['Linda', 'Katina', 'Alexandria', 'Jennifer']
len('Alexandria')
10
len(names)
4
names
['Linda', 'Katina', 'Alexandria', 'Jennifer']
names[1]
'Katina'
names[0]
'Linda'
names[-1]
'Jennifer'
names.append('Francine')
names
['Linda', 'Katina', 'Alexandria', 'Jennifer', 'Francine']
names[2]
'Alexandria'
names[2] = 'Alex'
names
['Linda', 'Katina', 'Alex', 'Jennifer', 'Francine']
names[1:3]
['Katina', 'Alex']
names[:3]
['Linda', 'Katina', 'Alex']
names[3:]
['Jennifer', 'Francine']
names[-2:]
['Jennifer', 'Francine']
lang = 'Python'
lang[0]
'P'
lang[-3:]
'hon'
for name in names:
print 'Hi ' + name
Hi Linda Hi Katina Hi Alex Hi Jennifer Hi Francine
for name in names:
if len(name) > 5:
print name + ", you need a nickname"
else:
print "Hi " + name
Hi Linda Katina, you need a nickname Hi Alex Jennifer, you need a nickname Francine, you need a nickname
for name in names:
for letter in name:
print "gimme a " + letter
print "What's it spell? " + name + "!"
gimme a L gimme a i gimme a n gimme a d gimme a a What's it spell? Linda! gimme a K gimme a a gimme a t gimme a i gimme a n gimme a a What's it spell? Katina! gimme a A gimme a l gimme a e gimme a x What's it spell? Alex! gimme a J gimme a e gimme a n gimme a n gimme a i gimme a f gimme a e gimme a r What's it spell? Jennifer! gimme a F gimme a r gimme a a gimme a n gimme a c gimme a i gimme a n gimme a e What's it spell? Francine!
for n in [0, 1, 2, 3, 4]:
print 'I love Python'
I love Python I love Python I love Python I love Python I love Python
range(5)
[0, 1, 2, 3, 4]
for n in range(5):
print 'I love Python'
I love Python I love Python I love Python I love Python I love Python
n = 1
while n < 100:
next = n + n
print str(n) + " and " + str(n) + " is " + str(next)
n = next
1 and 1 is 2 2 and 2 is 4 4 and 4 is 8 8 and 8 is 16 16 and 16 is 32 32 and 32 is 64 64 and 64 is 128
n = 1
while n < 100:
next = n + n
print str(n) + " and " + str(n) + " is " + str(next)
n = 1
while n < 100:
next = n + n
print str(n) + " and " + str(n) + " is " + str(next)
if n > 10:
print "My, these numbers are getting big"
n = next
1 and 1 is 2 2 and 2 is 4 4 and 4 is 8 8 and 8 is 16 16 and 16 is 32 My, these numbers are getting big 32 and 32 is 64 My, these numbers are getting big 64 and 64 is 128 My, these numbers are getting big
n = 1
while True:
next = n + n
print str(n) + " and " + str(n) + " is " + str(next)
n = next
if n > 100:
break
1 and 1 is 2 2 and 2 is 4 4 and 4 is 8 8 and 8 is 16 16 and 16 is 32 32 and 32 is 64 64 and 64 is 128
name = raw_input("Hi, what's your name? ")
print "Nice to meet you, " + name
Hi, what's your name? Catherine Nice to meet you, Catherine
Think of a phone book!
profession = {'Linda': 'Lion tamer',
'Alex': 'Ambassador to Antarctica',
'Katina': 'Rocketeer'}
profession
{'Alex': 'Ambassador to Antarctica', 'Katina': 'Rocketeer', 'Linda': 'Lion tamer'}
profession['Alex']
'Ambassador to Antarctica'
profession['Jennifer'] = 'Court Jester'
profession
{'Alex': 'Ambassador to Antarctica', 'Jennifer': 'Court Jester', 'Katina': 'Rocketeer', 'Linda': 'Lion tamer'}
profession['Jennifer'] = 'Feline Psychotherapist'
profession
{'Alex': 'Ambassador to Antarctica', 'Jennifer': 'Feline Psychotherapist', 'Katina': 'Rocketeer', 'Linda': 'Lion tamer'}
profession.keys()
['Linda', 'Alex', 'Katina', 'Jennifer']
profession.values()
['Lion tamer', 'Ambassador to Antarctica', 'Rocketeer', 'Feline Psychotherapist']
profession.items()
[('Linda', 'Lion tamer'), ('Alex', 'Ambassador to Antarctica'), ('Katina', 'Rocketeer'), ('Jennifer', 'Feline Psychotherapist')]
for (name, prof) in profession.items():
print name + " is a " + prof
Linda is a Lion tamer Alex is a Ambassador to Antarctica Katina is a Rocketeer Jennifer is a Feline Psychotherapist
dir(__builtin__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__IPYTHON__', '__IPYTHON__active', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'dreload', 'enumerate', 'eval', 'execfile', 'file', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
help(sum)
Help on built-in function sum in module __builtin__: sum(...) sum(sequence[, start]) -> value Returns the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start' (which defaults to 0). When the sequence is empty, returns start.
range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
sum(range(10))
45
import random
random.randint(1, 100)
2
random.choice([2, 8, 'twelve'])
2
capitals.py, a quiz game