OUTPUT "Here are the even numbers up to 100"
FOR i <-- 1 TO 100
IF i MOD 2 = 0
OUTPUT i
ENDIF
ENDFOR
OUTPUT "Finished"
The variable i has scope between lines 2 and 6. This is called block scope because i can only be used within the block of the for loop.
If a programmer were to try and use the variable before line 2 or after line 6, there would be a run-time error.
X <-- "test value"
FUNCTION message()
OUTPUT X
ENDFUNCTION
FUNCTION changeMessage()
OUTPUT "The message is:" + X
X <-- INPUT "What new message would you like?"
ENDFUNCTION
Variables with global scope are usually considered bad practice in most languages, due to the increased risk of name collisions.
- Function scope is similar:
FUNCTION square(n)
RETURN n * n
ENDFUNCTION
FUNCTION sumSquares(n)
total <-- 0
i <-- 0
WHILE i<= n:
total <-- total + square(i)
i <-- i + 1
ENDWHILE
RETURN total
ENDFUNCTION
Write a program for a user to input to input two numbers, then write the result of them being added together. The result from this should then be multiplied by three.
Do this in three ways, using function, module and global scopes.
Python One Liner:
print(sum([int(input('Input {} number'.format(i))) for i in ['first', 'second']]) * 3)
The variable i in Figure 1 only has scope between lines 3 and 7. Explain with reference to the variable i what scope means.
[1 mark]
VAT = 0.20
def calculations(amount):
tax = (VAT/amount)
print (tax)
totalCost = amount + tax
return totalCost
total = float(input("How much does the item cost? ")
print (calculations(total))
What does scope mean?
What is the scope of VAT?
What is the scope of tax?
What is the scope of totalCost?
What is the scope of total?
Why would it necessary for a variable to have limited scope?