[Tutor] cases with single if and an else clause

Dennis Lee Bieber wlfraed at ix.netcom.com
Wed Oct 6 19:35:33 EDT 2021


On Thu, 7 Oct 2021 03:53:11 +0530, Manprit Singh
<manpritsinghece at gmail.com> declaimed the following:


>def grades(glist, score):

>
>lst = [("F", 60),
>       ("D", 70),
>       ("C", 80),
>       ("B", 90),
>       ("A", 101)]
>
>try:
>    marks= int(input("Enter marks"))
>    grade = grades(lst, marks)
>

>
>My Next question is, in this particular scenario, where keeping the
>variable lst (which contains grade Characters and marks limits) as global
>and passing it as an argument to the function grades. So when this function
>is called, a copy of lst is created and it is destroyed upon exit from
>function.

	There is NO COPY... The parameter NAME "glist" is bound to the actual
list.

>>> lst = []
>>> def aFunc(lst):
... 	lst.append(len(lst))
... 	
>>> lst
[]
>>> aFunc(lst)
>>> lst
[0]
>>> 

	Names in Python are bound (connected) to objects. Python does NOT use
the "post office box" model where the names are fixed memory locations and
assignment copies the contents of the source box to the destination box.
Instead, in a somewhat simplified representation, Python uses "Post-It"
notes attached to strings which themselves connect to objects laying on the
floor. "Assignment" (binding) grabs a Post-It, writes the destination name
on it, finds a free string, attaches the Post-It (name) to the string, then
finds the source name's Post-It, follows its string to the relevant object,
and attaches the destination's string to the same object.

>>> aFunc(lst[:])
>>> lst
[0]
>>> 

	The use of [:] is what MAKES A (shallow) COPY of a list.

>
>As the variable lst serves no other purpose, why not keep this lst as a
>local variable inside the function grades .

	Python is byte-code interpreted at run time. Putting the list creation
inside the function means that the list is created each time the function
is executed, and deleted when the function exits. If the list (or other
structure) is large, creating it each time could be a significant slow-down
on the program.

>>> def bFunc():
... 	lst = [a]
... 	lst.append(len(lst))
... 	return lst
... 
>>> a = 1
>>> bFunc()
[1, 1]
>>> a = 3
>>> bFunc()
[3, 1]
>>> 

	If the list were not built at run time, the "def bFunc" compile (to
byte code) would fail since at the time, "a" does not exist.

	I used all capitals as a convention in Python that this name represents
a CONSTANT and should not be rebound or modified by code; code should only
access (read) the contents. I also treated it as a global (within the file)
constant to avoid passing it. 

	I would pass it if I were generating the score<>letter break points
dynamically (my example of "grading by the curve") as then it is not a
constant..



-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/



More information about the Tutor mailing list