First Steps
Open the terminal and open the Python prompt. You should see >>>
where you can start typing stuff. This is called the Python interpreter prompt.
Quit the Interpreter Prompt:
1 | [ctrl + d] or entering exit() # GNU/Linux or OS X |
Comments
1 | # This is a comment line. |
Literal Constants
Numbers
1 | 2 # a whole number |
Strings
1 | 'This is a string' # Single Quote |
Since we are discussing formatting, note that print always ends with an invisible “new line” character (\n) so that repeated calls to print will all print on a separate line each. To prevent this newline character from being printed, you can specify that it should end with a blank:
1 | print('a', end="") |
Output is:
1 | abc d* |
Escape Sequences:
1 | print('What\'s your name?') # Output is: What's your name? |
If you need to specify some strings where no special processing such as escape sequences are handled.
1 | print(r"Newlilnes are indicated by \n") |
Always use raw strings when dealing with regular expressions.
Variable
1 | _Rainy Rainy rainy # valid identifier |
Date Types
The basic types are numbers and strings.
Object
Python refers to anything used in a program as an object.
Logical And Physical Line
Python implicitly assumes that each physical line corresponds to a logical line.
1 | i = 5 |
is effectively same as
1 | i = 5; print(i) |
However, I strongly recommend that you stick to writing a maximum of a single logical line on each single physical line.
1 | s = "I love you. \ |
Sometimes, there is an implicit assumption where you don’t need to use a backslash. This is the case where the logical line has a starting parentheses, starting square brackets or a starting curly braces but not an ending one. This is called implicit line joining.
Indentation
Leading whitespace (spaces and tabs) at the beginning of the logical line is used to determine the indentation level of the logical line, which in turn is used to determine the grouping of statements.
1 | i = 5 |
Python will always use indentation for blocks and will never use braces.