In [1]:
x = int(input("Please enter an integer: "))
x
Out[1]:
In [2]:
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
In [7]:
# Measure some strings:
words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))
In [8]:
for w in words[:]:
if len(w) > 6:
words.insert(0, w)
words
Out[8]:
In [9]:
for i in range(5):
print(i)
In [12]:
list(range(5, 10))
Out[12]:
In [15]:
list(range(0, 10, 3))
Out[15]:
In [16]:
list(range(-10, -100, -30))
Out[16]:
In [17]:
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
print(i, a[i])
In [18]:
range(10)
Out[18]:
In [19]:
type(range(10))
Out[19]:
In [20]:
r1 = range(2)
In [23]:
dir(r1)
Out[23]:
In [24]:
iter(r1)
Out[24]:
In [25]:
ir1 = iter(r1)
In [27]:
dir(ir1)
Out[27]:
In [28]:
next(ir1)
Out[28]:
In [29]:
next(ir1)
Out[29]:
In [30]:
next(ir1)
In many ways the object returned by range() behaves as if it is a list, but in fact it isn’t. It is an object which returns the successive items of the desired sequence when you iterate over it, but it doesn’t really make the list, thus saving space.
We say such an object is iterable, that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that the for statement is such an iterator. The function list() is another; it creates lists from iterables:
In [31]:
list(range(2))
Out[31]:
In [32]:
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print("{0} equals {1} * {2}".format(n, x, n//x))
break
else:
# loop fell through without finding a factor
print(n, ' is a prime number')
In [33]:
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
In [4]:
while True:
pass
Note
Press I, I to interrupt the ipython kernel
In [5]:
class MyEmptyClass:
pass
In [6]:
def initlog(*args):
pass ## TODO: To implement this!
In [ ]: