Flow, Scope and Program Structure
A Python script is executed line by line, top to bottom. A function call interrupts the sequential execution of statements, causing the program to execute…
Flow of a program
A Python script is executed line by line, top to bottom. A function call interrupts the sequential execution of statements, causing the program to execute the statements within the function before continuing. Once the last statement in the function, or a return statement, has executed, flow of control is returned to the point immediately following where the function was called.Function definitions are packaged into an executable unit to be executed later. The code within a function definition executes only when invoked by a caller.
Follow it through. The first call has a = 4, so the if block runs: it prints 4 and returns 6, which is stored in x but not printed yet. The second call has a = 10, so the if is skipped, b is printed giving hi, and the returned value hi! is printed by the caller. Only then does the last line print the 6 that has been waiting in x.
A function that does not return a value actually returns the value None.
Variables and parameters are local
An assignment statement in a function creates a local variable for the variable on the left hand side of the assignment operator. It is called local because this variable only exists inside the function and you cannot use it outside.Functions calling other functions
Each function we write can be used and called from other functions.A template for programs
From now on, when we write a program, we will use this template: global variables first, then all the function definitions, then the program logic that calls them.A full program
This asks the user for the three coefficients of a quadratic and outputs how many real roots it has. Notice the shape: one function that does the thinking and returns an answer, then program logic that gathers the input, calls it, and prints the result.