Decomposition part 3 Flashcards
Write a function called “emphasize” that takes a string as a parameter. This function returns a modified version of the string:
- !!! will be added onto the end
Creating variables all at once at the start of a function
- Stylistic Note, not syntactically required but a stylistic approach
idenitifers (constants or variables) that are declared within the bidt of a function have a ——
local scope (the function)
identifiers (constants or variables) that are created outside the body of a function have a —–
global scope (the program)
- to the end of the start() call
Tell me the output of this program:
num1 = 10 def fun(): print(num1) def start(): fun() print(num2) num2 = 20 start()
10
20
When a variable is declared outside of a funtion, it becomes a
global variable
You can acess the contents of global variables anywhere in the program, in python, this can occur
even if the “global” keyword is not used
Why is the use of glonal variables bad programming style
they can be accidentally modified anywhere in the program
Difference between global variables and global constants:
global constants: used for values that remain constant
global variables: used for data that can be modififed during execution
Whats the output?
num = 1 def fun(): num = 2 print(num) def start(): print(num) fun() print(num) start()
1
2
1
passing variables does not…..
overwrite local variables
If you want to modify the value of a global variable from within the function, it will…. +ex (2)
not change it, just creates a local variable
ex:
~~~
name = 5 #global name
def fun():
name = 2 #local name
~~~
if you want to modify global variables from within the function, you need to
use the global keyword.
Prefacing the name of a variable with the keyword global in a function will indicate changes in the funtiuon will refer to the global variable rather than creating a local one
~~~
global <variable>
~~~</variable>
Tell me the output:
~~~
num = 1
def fun():
global num
num = 2
print(num)
def start():
print(num)
fun()
print(num)
start()
~~~
1
2
2
Boolean functions +ex (3)
- Return a Bolean value (T/F)
- Typically the Boolean function will ask the question about a parameter(s):
- ex: is it true that the string can be converted to a number? (def isNum(aString):)