Introduction - Python Bootcamp
- Why use Python?
- Some challenges in dealing with Python
- How Python works
- Some basics
Why use Python?
- Python is powerful and easy.
- Python comes with “batteries included.” There are lots of useful and powerful packages in the standard library.
- Programs are short, clear, and concise
- Whitespace is required, preventing hopelessly unreadable code
- There’s one obvious way to do it
Some challenges in dealing with Python
- The compiler will not stop you from writing nonsense sense but is actually wrong
- Some errors won’t show up unless the actual line of code is run, meaning that you have no idea whether anything works until you test it.
How Python works
- Each line of code is parsed into its syntax
- The syntax tree is turned into byte code which is executed by the interpreter
- Only syntax errors are caught in advance; runtime errors are reported as they happen. For example, the compiler will tell you if you’ve forgotten a colon, but it won’t tell if you’re calling something on a number that requires a string.
- Start out by running
pythonor an IDE such as
Spyderto try out typing things in the interpreter.
- Typing directly into the interpreter is called a
REPL: Read Eval Print Loop. It reads your input line-by-line and prints results.
The simplest thing you can type is an expression. The simplest expressions are just literals, which evaluate to themselves. Note that Python uses single and double-quotes interchangeably, and doesn’t distinguish between characters and strings like many other languages.
>>> 7 7 >>> 7.5 7.5 >>> "H" 'H' >>> "Hello world!" 'Hello world!'
You don’t have to do much work to assign values to variables. What are called “variables” in most programming languages are technically called “names” in Python. We’ll worry about what that means later.
>>> x = 7 >>> x 7 >>> x = 7.5 >>> x 7.5 >>> x = "H" >>> x 'H' >>> x = "Hello world!" >>> x 'Hello world!'
Note that you don’t have to declare variables in advance and you don’t tell Python what type (string, integer, etc.) a variable will have.
Handy built-in functions
These are very useful when you’re trying to sort out issues in the REPL. You’ll rarely need to use these in real programs.
type(x): see what type
>>> type(7) <type 'int'> >>> type(7.0) <type 'float'> >>> type("H") <type 'str'> >>> type("Hello world!") <type 'str'>
dir(): see what names are bound at the moment
dir(x): see all methods that
id(x): get the identity (effectively memory address) of what