More Events
1
CS 110
Events: Ways of Dealing with User Input
Events allow programs to listen to particular events (clicks, drags, etc.) and execute parts of a program based on the input. Events have two parts:
2
setup_listener("LEFT-CLICK", do_something)
3
We use this function to set the listener up.
A function name to run when the event happens (handler) that is defined to have exactly 1 input
Setting an Event Listener on the Pop-up Window
The event to listen for (a special string specified by Python)
Variable Scope
4
Scope
5
Scope 1: Consider the following program...
def demo_1(name):
greeting = 'Welcome, ' + name
demo_1('Jimmy')
print(greeting)
�What will print to the screen?
6
Scope 1: Local variables cannot be accessed outside function
def demo_1(name):
greeting = 'Welcome, ' + name
demo_1('Jimmy')
print(greeting)
�TAKEAWAY: If you want access to a value after the function ends, you have to return it.
7
local variable
greeting variable was local to the demo_1 function. Throws error.
Scope 2: Which name will print to the screen?
name = 'Lindsay'
def demo_2(name):
print(name)
demo_2('Walter')
8
Global variable
Parameters are local variables. �They take precedence over global variables
Scope 2: Which name will print to the screen?
name = 'Lindsay'
def demo_2(name):
print(name)
demo_2('Walter')
TAKEAWAY: Local variables take precedence over global variables.
9
Global variable
Parameters are local variables. �They take precedence over global variables
Scope 3: Global variables can be accessed inside a function
name_1 = 'Lindsay'
def demo_3(name):
print(name)
print(name_1)
demo_3('Walter')
10
local variable
global variable
Scope 4: Global variables can updated with global keyword
name = 'Lindsay'
def modify_name(new_name):
global name
name = new_name
print(name)�modify_name('Walter')�print(name)
11
Scope 5: Without global keyword, Python assumes you’re creating a new local variable
�name = 'Lindsay'
def modify_name(new_name):
name = new_name
print(name)�modify_name('Walter')�print(name)
12