...
Code Block |
---|
a = 1
b = 2
a, b = b, a
print(a,b) |
Fibonacci series generator
The first two numbers of the series is always equal to 1, and each consecutive number returned is the sum of the last two numbers - the below code uses only two variables to get the result.
Code Block |
---|
def fib():
a, b = 1, 1
while 1:
yield a
a, b = b, a + b
# testing code
import types
if type(fib()) == types.GeneratorType:
print("Good, The fib function is a generator.")
counter = 0
for n in fib():
print(n)
counter += 1
if counter == 10:
break |
Split string as list
Code Block |
---|
sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
print(words) |
Filter positive numbers only - 1
Code Block |
---|
numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]
newlist = []
for number in numbers:
if number>0:
newlist.append(number)
print(newlist) |
Filter positive numbers only - 2
Code Block |
---|
numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]
newlist = [int(x) for x in numbers if x > 0]
print(newlist) |