Does Python have a static variable like C has? I like to avoid a global variable for the usual reasons.
Note: A static variable in a C function will retain its last value.
As far as I know, Python does not have an official static variable, but you can easily mimic one ...
# a mutable object like a list element as default argument # will act like a static variable since its address is fixed def static_num2(list1=): list1 += 1 return list1 print static_num2() # 1 print static_num2() # 2 print static_num2() # 3 etc.
This is cool, so initially list1 is zero to start the count!
How can you wrap that into a normal bread and butter function?
Well, here would be an example of a "bread and butter" function using the counter ...
def f1(str1, count=): # your code str1 = str1 + " and butter" # the counter count += 1 # return a tuple return count, str1 print f1("bread") # (1, 'bread and butter') print f1("bread") # (2, 'bread and butter') print f1("bread") # (3, 'bread and butter')
We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.