Assigning types to variables as values
a_var = str
a_var(123)
random choice
#from random import choice
a, b, c = float, int, str
for i in range(5):
j = choice([a,b,c])(i)
print(j, type(j))
gen_fails = (i for i in 1/0)
lazy evaluation
gen_succeeds = (i for i in range(5) for j in 1/0)
print('But obviously fails when we iterate ...')
for i in gen_succeeds:
print(i)
Usge of *args
def a_func(*args):
print('type of args:', type(args))
print('args contents:', args)
print('1st argument:', args[0])
a_func(0, 1, 'a', 'b', 'c')
usage of kwargs
def b_func(**kwargs):
print('type of kwargs:', type(kwargs))
print('kwargs contents: ', kwargs)
print('value of argument a:', kwargs['a'])
b_func(a=1, b=2, c=3, d=4)
Unpacking of iterables
val1, *vals = [1, 2, 3, 4, 5]
print('val1:', val1)
print('vals:', vals)
if else for
for i in range(5):
if i == 1:
print('in for')
else:
print('in else')
print('after for-loop')
usage of break
for i in range(5):
if i == 1:
break
else:
print('in else')
print('after for-loop')
conditional usecase
a_list = [1,2]
if a_list[0] == 1:
print('Hello, World!')
else:
print('Bye, World!')
### Usage of while
i = 0
while i < 2:
print(i)
i += 1
else:
print('in else')
Interning of string
hello1 = 'Hello'
hello2 = 'Hell' + 'o'
hello3 = 'Hell'
hello3 = hello3 + 'o'
print('hello1 is hello2:', hello1 is hello2)
print('hello1 is hello3:', hello1 is hello3)