Tutorial by Examples

Prefer dict.get method if you are not sure if the key is present. It allows you to return a default value if key is not found. The traditional method dict[key] would raise a KeyError exception. Rather than doing def add_student(): try: students['count'] += 1 except KeyError: ...
To switch the value of two variables you can use tuple unpacking. x = True y = False x, y = y, x x # False y # True
Python will implicitly convert any object to a Boolean value for testing, so use it wherever possible. # Good examples, using implicit truth testing if attr: # do something if not attr: # do something # Bad examples, using specific types if attr == 1: # do something if att...
It is good practice to test the calling program's __name__ variable before executing your code. import sys def main(): # Your code starts here # Don't forget to provide a return code return 0 if __name__ == "__main__": sys.exit(main()) Using this pattern ens...

Page 1 of 1