# if - elif - else conditions
guess_me = 7
if guess_me == 7:
print('right')
elif guess_me > 7:
print('too high')
else:
print("too low")
start = 1
# while loop
while 1:
if start < guess_me:
print('too low')
elif start == guess_me:
print('found it')
elif start > guess_me:
print("oops")
print('start = ', start)
break
start += 1
# for loop
a_list = []
for i in range(3, -1, -1):
a_list.append(i)
for i in a_list:
print(i)
# list deriving
even_number = [number for number in range(10) if number % 2 == 0 ]
print(even_number)
odd_number = [number for number in range(10) if number % 2 != 0 ]
print(odd_number)
# generator (this is fun! )
for got_number in ('Got %s' %number for number in range(10)):
print (got_number)
# function
def good():
return ['Harry', 'Ron', 'Hermione']
print(good())
a = good()
for i in a:
print(i)
# generator function
def generator_function(first = 0, last = 20, step = 5):
number = first
while number < last:
yield number
number += step
for i in generator_function():
print(i)
b = generator_function(0, 100, 20)
print(type(b))
for i in b:
print(i)
def generator_function_two(first = 1, last = 9 ):
time = 0
for i in generator_function(first, last, 1):
time += 1
if i % 2 != 0:
yield i
for count, number in enumerate(generator_function_two(), 1):
if count == 3:
print('the third number is ', number)
# decorator
def test(func):
def new_fuction(*args, **kargs):
print('starting ', func.__name__)
result = func(*args, **kargs)
print('the result is ',result)
print(func.__name__, ' running complete')
return result # easy to miss
return new_fuction
@test
def add_int(first, second):
return first + second
add_int(3, 6)
# define exception
class OopsException(Exception):
pass
try:
raise OopsException('what??')
except OopsException as ex:
print("wtf")
# zip function
list_one = [1, 2, 3]
list_two = [4, 5, 6]
for i in zip(list_one, list_two):
print(i)
for j in i:
print(j) # ignore this
# unzip
total_list = zip(list_one, list_two)
for list in zip(*total_list):
print(list)
网友评论