Monday, December 17, 2018

Python Variables, Conditionals, Loops, Functions, just a feel.

Are you local? Or global?
# Example variables
p, q = 10, 20
t = True
f = False
s = "a string"
d = 33.567
x = 123
y = 456

def function_a():
    global y
    x = 987
    y = "banana"
    print ( x ) 

function_a()
print ( x )
print ( y )
del x ## remove a variable and undefine it
Conditionals
# Example conditionals
if True:
    print ( "It is true!" )

if i in [ 1,2,3 ]:
    print ( i )

x, y = 2, 9
if ( x > y ):
    z = x - y
elif:
    z = x + y
else:
    z = 0
Loops
# Example loops
for i in range(100):
    print ( i )

days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ]
for d in days:
    print ( d )

while True:
    print ("It is still going!")
## Ok, don't do this, this is an infinite loop! 
## You just did!? just type [Ctrl-C], phew...

Functions
# Example functions
def function_q():
    pass

def function_x( a,b ):
    return a + b

def functiona( a, b=100 ):
    c = a
    for i in range( b ):
        c += i
    return c

def function_y( list=[] ):
    pass

def function_z( hash={} ):
    print ( "in function_z" )
    ## without return, function returns None

function_q()
function_x( 1,2 )
function_y()
function_z()

## Try these, can you guess what will be printed?
print (function_z())
print (function_z)

No comments:

Post a Comment