Presentation on theme: "Q and A for Chapter 3.4 – 3.14 CS 104 Victor Norman."— Presentation transcript:
Q and A for Chapter 3.4 – 3.14 CS 104 Victor Norman
Creating new functions Q: Can you create new functions with new names, or just use the one they show in the book? A: You can create any function you want with any legal name (legal identifier, like for variables). You must define the function before calling it.
Creating new functions def aFunc(param1, param2): # code indented 4 spaces that does stuff print param1 + param2 def yell(param1): # param1 must be str print param1.upper() aFunc(3, 4) aFunc(“Hello”, “world”) hi = “Greetings, earthling.” yell(hi)
String functions Q: Why create functions that work with strings? Functions to compute math stuff are obvious. A: Lots of computing is with strings. def prependTime(outStr): # code here to get the time print time + “: “ + outStr
Function Parameters Q: Can functions take more than 1 or 2 parameters? A: Yes: a function definition specifies how many parameters it takes. The function call must provide that many arguments. (Reminder: a function call evaluates its arguments before calling the function, where the parameters point to those values within the function code.)
Functions 2 Q: Can you define a function inside a function? A: You can, but you better not until you’ve been working with python for a few years. And, besides, that inner function definition goes away when the outer function call returns, so it isn’t very useful.
Stack frames! Help! Q: I need help with this stack frames business. Does python actually do this? A: Python does this internally, to keep track of what code is calling what code, etc. You don’t see this when it is running. Check this out.this
Local Variables Q: I don’t understand local variables. A: (That’s not a question… :-) A local variable in a function is a name that refers to a value, but is created when the function code is run, and is deleted when the function returns. (A parameter is a local variable that is initialized to refer to the value passed in by the corresponding argument.)
References to functions Q: What happens when you call a function without ()? Like this: supposed print_twice was defined, but you “call” it this way: print_twice (without the ()) A: This is just a reference to the function print_twice. It is a reference to where the function is defined in memory. It is not a function call.
void functions? Q: What is the point of a void function that doesn’t return something? A: Functions that don’t return things usually: print something, or, alter some object that is passed in. So, they can be very useful.
from someModule import * Q: Why not always just import everything from a module? So, that you don’t have to do module.function or module.variable every time? A: You will pollute the namespace by doing it this way. But, that’s OK… for now… (We’ll talk about this much much later.)