0% found this document useful (0 votes)
6 views30 pages

Understanding Variable Scope in Python

The document covers key concepts in programming, including the scope of variables (local vs global), modular programming, and the use of Python modules for graphics. It explains the importance of defining variable scope to avoid unintended side effects and emphasizes the benefits of modular programming for managing complex problems. Additionally, it introduces graphics programming with examples of creating and manipulating drawable objects using the cs1graphics module.

Uploaded by

The Prince
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views30 pages

Understanding Variable Scope in Python

The document covers key concepts in programming, including the scope of variables (local vs global), modular programming, and the use of Python modules for graphics. It explains the importance of defining variable scope to avoid unintended side effects and emphasizes the benefits of modular programming for managing complex problems. Additionally, it introduces graphics programming with examples of creating and manipulating drawable objects using the cs1graphics module.

Uploaded by

The Prince
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CCE20003 HGU

CCE20003 PROGRAMMING I
Lecture 9

Spring 2015

Department of Computing
The School of EE & Computing
Adama Science & Technology University
OUTLINE CCE20003 HGU

Scope of a variable
Modules
Graphics
SCOPE OF A VARIABLE CCE20003 HGU

def test(): What will happen with this program?


print a Unfortunately, it will be canceled !
a = 77
Why ? Variable a is local but not global.
print a

a= 99 A local variable a is undefined when


test() it is used in the first print statement !

What does it mean by local or global ?


Why local?
CCE20003 HGU

LOCAL VARIABLES
A variable is local if its scope is restricted inside
a function: It appears when a function is called, exists
during execution of the function, and disappears
when the function is terminated.

Local variables include:


- parameters of a function
- variables on the left hand side of an assignment
statement in a function
CCE20003 HGU

Evaluating a𝒙𝟐 + bx + c
def quadratic( a, b, c, x ):
quad_term = a * x ** 2 Which variables are local?
lin term = b * x
return (quad_term + lin_term + c) The variables in blue color!
Why?
print quaratic(2, 4, 5, 3)

a 2
b 4
c 5
x 3
CCE20003 HGU

Global variables
Variables defined outside of all functions are called
global variables. These are be referenced by their names.
Global variables can be used inside a function:

def turn_right():
for i in range(3):
hubo.turn_left()
hubo = Robot()
CCE20003 HGU

Why global variables?


Well, ….convenient sometimes!
Consider a program that evaluates 2*𝑥 2 + 5x + 4
while changing x.
What if a global variable is changed by mistake ?
qudratic(): x=3
quad_term =a * x ** 2 print quadratic()
lint_erm = b * x …………….
return (quad_term + lin_term + c) x = 5
a=2 print quadratic()
b=5 a = “Joseph” by mistake
c =4 print a
……
x= 2
Unpredictable side effects! print quadratic()
CCE20003 HGU

Modular programming
A software development method to decompose a large
problem into small problems, develop and test the
program for solving each problem, independently, and
combine all these programs to construct a large program.
A small program itself is a function or consists of multiple
functions.

In modular programming, the input(parameters) of every


function and its output(return values) should be well-
defined. Why ?
CCE20003 HGU

Function calls
By explicitly providing the arguments corresponding to
the parameters, you do not need to worry about what is
happening inside a function.

What if global variables are used instead of parameters?


You should have to remember all global variables used in
a function so as to avoid side effects by modifying
these by mistake.

In large programs, using global variables is dangerous, as


they could be modified by mistake.
CCE20003 HGU

The program revisited

def test(): def test():


print a global a
a is local. a is global.
a = 77 print a
print a a = 77
print a

a= 99
a= 99
test() test()
CCE20003 HGU

def turn_left(): def turn_right():


global hubo_direction global hubo_direction
for I in range(3):
hubo.turn_left()
hubo.turn_left()
hubo_direction += 90 [Link] -= 90
hubo = Robot() hubo = Robot()
hubo_direction = 0 hubo_direction = 0
turn_left() turn_left()

We can change the value of a global variable inside a


function by explicitly defining it as global in a function!
CCE20003 HGU

def f(a):
print "a = ", a Guess what will be printed.
def g():
a=7 a = Letter a
f(a+1) a = 3.14
print “a = “, a a = Letter a
a = “Letter a” a= 8
print “a = “, a a=7
f(3.14) a = Letter a
print “a = “, a
g()
print ‘a = ‘, a
CCE20003 HGU

def swap(a,b): What will be printed ?


a, b = b, a 555 33 or 33 555 ? Why?
x, y = 33, 555
swap(x, y)
print x, y
def swap(a,b):
Can you fix the program so
a, b = b, a
that it swap the two values ?

x, y = 33, 555
swap(x, y)
print x, y
MODULES CCE20003 HGU

A Python module is a collection of functions that are


grouped together in a file. Python comes with a large
number of useful modules.
- math for mathematical functions
- random for random numbers and shuffling
- sys and os for accessing the operating system
- urllib to download files from the web
- cs1robots for playing with robots such as Hubo
- cs1graphics for graphics
- cs1media for processing photos
We can also create our own modules.
CCE20003 HGU

You can get information about a module using the help


function:
>>> help("cs1media")
>>> help("cs1media.picture_tool")

In large programs, using global variables is dangerous


as they can be modified by mistake.
CCE20003 HGU

Decomposition and Abstraction


With a clear interface to a module, you can easily use a
module. For example, cs1robots is a module that
implements the object type, Robot. Robot can easily be
used without understanding how it is implemented.

In Python, a class that generates objects(instances) has


attributes (data) and methods.
Object-oriented programming
CCE20003 HGU

How to use a module

import math
print [Link]([Link] / 4)

from math import *


print sin(pi / 4)
print [Link] Why an error?
from math import sin, pi
print sin(pi / 4)
print pi
print cos(pi/4) Why errors?
print [Link]
CCE20003 HGU

from cs1robots import *


create_world()
hubo = Robot()
[Link]() Which one do you prefer ?
hubo.turn_left() Well, ……

import cs1robots The second approach is


create_world() recommended. Why?
hubo = [Link]()
[Link]()
hubo.turn_left()
GRAPHICS: CS1GRAPHICS CCE20003 HGU

Creating canvas to draw on

from cs1graphics import *


canvas = Canvas(400, 300)

[Link](“light blue”)
[Link](“CCE20003 Drawing Exercise”)

Reference: [Link]
Read tutorial(Chapter 3)
CCE20003 HGU

canvas = Canvas(400,300)

0 399

canvas
299
CCE20003 HGU

DRAWABLE OBJECTS
1. Circle(radius)
2. Square(side)
3. Rectangle(width, height)
4. Polygon(………..)
5. Path(……….)
6. Text(message, font_size) fillable objects
7. Image(image_filename)
CCE20003 HGU

How to draw an object: Square


sq = Square(100)
[Link](sq) Add a square to canvas.
[Link](“blue”)
[Link](“red”)
[Link](5) Move the reference point
[Link](200,200) of the square to (200, 200).
(absolute move)
for i in range(100):
[Link](1,0) Relative move with respect
to the current reference
point.
CCE20003 HGU

The previous code to


initialize the canvas.
sq = Square(100)
[Link](sq)
[Link](“blue”)
[Link](“red”)
[Link](5)
[Link](200,200)
Animation
for i in range(100):
[Link](1,0)
A circle and a rectangle
can be created in a similar
manner. For other drawables
read the reference.
CCE20003 HGU

Depth
rect = Rectangle(150, 75)
[Link](rect)
[Link]("yellow")
[Link](280, 150)

Changing depths:
[Link](10)
[Link](20)

The default value is 50.


CCE20003 HGU

Rotation (wrt the reference point)


[Link](45)
Scaling wrt the reference point)
[Link](1.5)
[Link](0.5)
Fade-out:
for i in range(80):
[Link](0.95)
[Link](sq)
Mirror flipping (around an axis).
[Link](5)
CCE20003 HGU

Layer: Grouping drawables together

car = Layer()
tire1 = Circle(10, Point(-20,-10))
[Link]('black')
[Link](tire1)
tire2 = Circle(10, Point(20,-10))
[Link]('black')
[Link](tire2)
body = Rectangle(70, 30, Point(0, -25))
[Link]('blue')
[Link](60)
[Link](body)
CCE20003 HGU

[Link](110,180)
[Link](20)
[Link](car)

180

110
CCE20003 HGU

The whole layer can be transformed as a single


object !
for i in range(50): Relative transformations!
[Link](2, 0)
for i in range(22):
[Link](-1)
for i in range(50):
[Link](2,-1)
for i in range(22):
[Link](1)
for i in range(50): for i in range(10):
[Link](2,0) [Link](1.05)
[Link](90)
CCE20003 HGU

Color interpolation

1 color2 =(r2, g2, b2)


1-t
0 t
(1 - t) * color1 + t * color2

color1 = (r1, g1, b1)

def interpolate_colors(t, color1, color2):


r1, g1, b1 = color1
r2, g2, b2 = color2
return (int((1-t) * r1 + t * r2), int((1-t) * g1 + t * g2),
int((1-t) * b1 + t * b2))
CCE20003 HGU

Color conversion
From a color name to an (r,g,b) tuple
Color(color).getColorValue()

print Color(“red”).getColorValue()
(245, 0, 0)

How about the reverse conversion (from rgb to color name)?


Not available yet. Why?

You shall practice color interpolation and conversion in the next


lecture!

You might also like