In [ ]:
a = 1.0
if a == 0.0:
print('zero')
elif a > 10.0 or a < -10:
print("too big")
else:
print("close enough")
Things to try :
In [ ]:
for i in [1,3,-1,10,100,0]:
#for i in range(1,10,2):
if i<0:
continue
if i>10:
print("break")
break
if i<3:
pass
print("pass")
print(i)
else:
print("only if there is no break")
Things to try:
The above mentioned for-loop can be compacted in python (not recommmended, as your readability goes down the drain):
In [ ]:
for i in [1,3,-1,10,100,0]:
if i<0: continue
if i>10: print("break"); break
if i<3: pass; print("pass")
print(i)
else:
print("only if there is no break")
In [ ]:
a = 0
sum = 0
while a<10:
a += 1
sum += a
print(a,sum)
if sum>100:
break
else:
print("final sum",sum)
Things to try:
In [ ]:
def mysqrt(x):
# this is my sqrt function (comment vs. docstring)
import math
if x < 0:
return -math.sqrt(-x)
else:
return math.sqrt(x)
for x2 in [-4.0,0.0,4.0]:
print(mysqrt(x2))
print(x2)
In [ ]:
dir(mysqrt)
In [ ]:
print(mysqrt.__doc__)
Functions can have default arguments:
In [ ]:
def mysqrt(x,verbose=False,classic=False):
import math
if classic:
if verbose: print("classic",x)
return math.sqrt(x)
if x < 0:
if verbose: print("fixing",x)
return -math.sqrt(-x)
else:
if verbose: print("correct",x)
return math.sqrt(x)
print(mysqrt(-4.0))
print(mysqrt(-2.0,True))
print(mysqrt(-2.0,classic=True))
In [ ]:
try:
print(mysqrt(-2.0,classic=True))
except:
print("some error, deal with it")
Scope of variables: as in other languages, objects inside a function are not visible outside and vice versa, but again, perhaps with a tiny twist
In [ ]:
a1 = 1.0
def testa(x):
global a1
print(a1+x)
a1 = a1 + x
# y = a1 - x
testa(2.0)
testa(2.0)
# print(y)
In [ ]:
import math
print(math.pi)
def mypi(x):
# this will overwrite \pi !!!
math.pi = x
return {x,x}
a=mypi(3)
print(math.pi)
print(x2)
print('a',a)
#print("a=%g" % a)
print(type(a))
print(type(mypi))
In [ ]: