Python tips

Anh-Thi Dinh

Miscellaneous

  • ; is not used, use spaces instead!
  • If you wanna 2 or more commands in 1 line, you can use ; to separate them.
  • Tab size usually is 4.
  • Lines can be broken with just an Enter, you also use \\ between the lines if you want.
  • From Python 3.6, you can use 1_000_000 for the number 1000000.
  • from __future__ import <package> allows current version of python to use <package> which is only available in the "future" version of python.
  • if __name__ == "__main__": determines the main running file of codes. The codes inside this command only run if the file containing it is the main executed file! (read more)
  • If we don't need to mention some variable, use _:
    • 1for _ in range(2):
      2  print("Thi")
      1Thi
      2Thi
 

Swap 2 variables

1a, b = b, a

Clear variables

1# Clear (without confirmation) a variable from workspace
2del <var>
3%reset_selective <var>
1# Check if available and then delete
2if '<var>' in globals(): del <var>
3# use locals() inside a def
1# Clear all variables
2%reset # with confirmation
3%reset -f # without confirmation

References