Day 4: Class vs. Instance
Day 4: Class vs. Instance
+ 18 comments This is just depressing. I'm old now :(
+ 43 comments After much banging of my head, I Googled "local variable referenced before assignment", because I kept getting the "UnboundLocalError: local variable 'age' referenced before assignment" error. One of the answers suggested I use 'global' for Python and it worked! The workaround is to pass a parameter instead of using the more dangerous 'global' keyword, but since we can't change the calling code, 'global' is the way to go. If someone solved this without using 'global' for Python3, please post your solution. It would be good to learn better ways.
class Person: def __init__(self, initialAge): # Add some more code to run some checks on initialAge self.age = 0 if initialAge < 0: print("Age is not valid, setting age to 0.") else: self.age = initialAge def amIOld(self): # Do some computations in here and print out the correct statement to the console if age < 13: print("You are young.") elif 13 <= age < 18: print("You are a teenager.") elif age >= 18: print("You are old.") def yearPasses(self): # Increment the age of the person in here global age age += 1
+ 8 comments Am I the only one who think this problem is poorly explained?
+ 28 comments The C# Problem is broken. It adds another newline at the end of the final test case, so it's impossible to match the expected solution.
"Age is not valid, setting age to 0. You are young. You are young.
You are young. You are a teenager
You are a teenager You are old.
You are old. You are old.
"
When it is saying it should be:
"Age is not valid, setting age to 0. You are young. You are young.
You are young. You are a teenager
You are a teenager You are old.
You are old. You are old. "
I can't modify the main, so I'm stuck failing test cases.
+ 2 comments But you're still a teenager if you're 18...
Sort 1721 Discussions, By:
Please Login in order to post a comment