Today we continue with functions. We will talk about variable scope within functions, and when it is appropriate to reference variables outside of your functions. We'll also expand our view of functions to calling functions from within functions. Classtime will include several exercises and practice with functions.
You should have read all of it by now.
We will discuss and learn about:
This program reads a sentence from a user, and then splits it into its words. However, sometimes text has punctuation so this function removes that too!
def tokenize(text):
# Lowercase
text = text.lower()
# This removes basic punctuation!
text = text.replace('.','').replace('?','').replace(',','')
# Split on space characters and return the List of strings
return text.split()
text = input("Sentence: ")
tokens = tokenize(text)
tokens.sort()
print(tokens)
We've done this before, but now in function form: test if an integer is prime! No more rewriting this code now that we have a function:
def isprime(num):
if num <= 1:
return False
for i in range(2, int(num/2)+1):
if num % i == 0:
return False
return True # If we reached here, then no divisor was found.
x = int(input("Prime test: "))
print( isprime(x) )