If you have a script that you want to run multiple times without having to restart your shell session, you can turn it into a custom function.
In this case, instead of asking for the user's input, you must type in the name of the function along with what you WOULD HAVE typed as your answer to the question.
These custom functions work just like any other pre-defined function (like len()), except that they aren't pre-defined - you provide the definition!
The name of your function will be in blue text in your script - unless you've changed it in the settings.
Once your function has executed, the variable(s) assigned (here, age) will no longer be accessible.
Learn More
NOTE! The last print command in the video script starts out with DOUBLE quotes because there is an apostrophe in "can't".
Remember that you can also prefix the apostrophe with the backslash "\" to keep it as normal text (a process called escaping), and not as a string delimiter. (We covered this in Tutorial 6.)
A function definition starts with def, followed by the function name, the parameter(s) in ( ), a colon :, and then finally an indented function body:
def sayhello(who):
print('Hello, ' + who + '!')
print("It's a lovely day.")
print("La, la, la, la...")
hello.py
Note that the 3rd print function is outside the indented block. It therefore is not part of the sayhello() function. It executes when the script is run, not when the function is called.
There's so much more to functions. And functions are fun, especially when you write the "fruitful" kind, i.e, the ones that return a value rather than just printing stuff. Learn how in User-Defined Functions.
Practice
Write a function that prints out how many vowels are in a given word. Try in IDLE shell.
Write a function that tests a given word for whether or not it includes all of the five vowel characters. If it does, it should print out "Yay! All 5 vowels in the word."; otherwise it prints out "x is missing" for every missing vowel x. Note 'a' in 'bat' is how you test for substringhood. Try it in IDLE shell.
>>> def all_vowels(wd):
if 'a' in wd and 'e' in wd and 'i' in wd and 'o' in wd and 'u' in wd:
print("Yay! All 5 vowels in the word.")
else:
if 'a' not in wd:
print("'a' is missing.")
if 'e' not in wd:
print("'e' is missing.")
if 'i' not in wd:
print("'i' is missing.")
if 'o' not in wd:
print("'o' is missing.")
if 'u' not in wd:
print("'u' is missing.")
>>> all_vowels('penguin')
'a' is missing.
'o' is missing.>>> all_vowels('unfashionable')
Yay! All 5 vowels in the word.>>>
Explore
Think Python has many sections on functions, all useful: