JackBennett

Python Scopes & Functions

# Scopes, the idea that variables only exist in certain contexts.
## Many don't see that variables in python exist down and to the right. So every
## Many seem to miss that this total needs to be outside for
total = 0
for num in listOfNumbers:
    total = total + num
print("total should be 15 here: " + str(total) )
# total needs to exist outside of the for block to aggigate the value

name = 'global'
def scopeAExample():
    name = 'scopeB'
    print(name)

def scopeBExample():
    global name
    name = 'scopeB'
    print(name)

print(name) # global
scopeAExample() # scopeA
print(name) # global
scopeBExample() # scopeB
print(name) # scopeB
# -------------------




# Function calls with parameters and returns.
## Completely forgeign concept to anyone in the class.
def callMe(maybe): ## accept 1 value to the fucntion about to be run, put it in the variable 'maybe'
    return 'I will call: ' + str(maybe) ## Give back a string that also uses the provided value

def callMeBroke(maybe): ## accept 1 value to the fucntion about to be run, put it in the variable 'maybe'
    'I will call: ' + str(maybe) ## Give back a string that also uses the provided value

print( callMe('ishmael') ) ## print whatever callMe gives us back, in this case a string.
print( callMeBroke('Sue') ) ## as callMeBroke doens't return a value, it will implicitaly return the none value type of 'None'
# -------------------


# example problems compounding.
# I see far too much like this that while it does work, demonstrates quite a severe lack of being able to read and UNDERSTAND what is going on.
import csv
with open('learning.py') as datastream:
    for line in datastream:
        # print each line or something
        continue

def searchForLine():
    with open('learning.py') as datastream:
        for line in datastream:
            if line.startswith('#'):
                'this was a comment'
            else:
                'this was code'

# things to note:
# 1. Repeatedly opening the same file
# 2. Imports a library but is actually used
# 3. Doesn't make any variable for re-using data, like the contents of the file
# 3a. Doesn't make a function opening the file and reading it's contents, instead always repeating the for loop.