Lesson Notes
Imagine if there were no traffic rules and intersections were a free-for-all where only the bravest made it through.
You quickly realize that it's much easier (and safer) if we all agree on a basic set of rules or conventions.
In many programming languages, it is not possible to have executable code in global scope. Executable code is required to be in a function.
Global Variables, data stored in global scope, are dangerous, inefficient, and even tomfoolery.
Basically, Global Variables are BAD and a sign of LAZY coding.
Using a main()
function eliminates the need for global scoped data
main
instead of 'start' or 'begin' because many other languages require a main()
functionWe can define a main()
function just like any other function
def main():
#all of the code you would have put in global scope goes here
But the above is just a definition. We need to call our main
, otherwise our program won’t run:
def main():
statements()
#I usually put main at the end of my program, but you can put it anywhere
main() #the call to main() MUST go at the end of your program
You can put your definition for the main
function anywhere in the file, but the call to main()
should always go last.
Function documentation uses syntax called Docstrings
def myFunction(x):
"""
This function does stuff
args: x
return: int
"""
return x
docstring format:
"""
<description>
args: <list of arguments>
return: <type of return>
"""
Every function, except main()
, should begin with a docstring containing a description, a list of arguments, and a return type
From now, all functions except
main()
, need a docstring
Conventions we will follow:
set of patterns that occur often in programming
accumulator = starting_value
for i in list:
accumlator = accumulator <op> i
def removeVowels(text):
vowels = "aeiou"
vowels += vowels.upper() #list of vowels
newtext = "" #accumulator - starting value is empty string
for ch in text:
if ch not in vowels:
newtext += ch
return newtext
def main():
mystr = "compsci"
print(removeVowels(mystr))
mystr = "LEEEEEEROYJENKINS!"
print(removeVowels(mystr))
main()