Python is a dynamic, interpreted language. You don't have to type declarations of variables, parameters, functions, or methods in your source code. This results in very code short with an extremely flexible script style. Python automatically keeps track of all the types of values at program runtime and automatically flags code that does not make sense to the interpreter as it runs.
The best way to understand Python is to see how the code works by running the Python interpreter from the command line and typing your programs right into the interpreter's shell.
Have you ever asked a programming question like...
"What happens if I add an int to a list?"
Typing it into the interpreter is the easiest way to see what happens.
The interpreter makes it easy to experiment with integers, string variables and operators. Also, the interpreter throws an Exception; a runtime error, if the code tries to read a variable that has not been assigned a value. Just like C++ and Java, Python is case sensitive so _r_ and _R_ are different variables. Unlike C++ and Java, Python does not require a semicolon at the end of each statement. The end of a line marks the end of a statement. Python is also heavily indented. Python comments begin with a '#' and extend to the end of the line. ### A closer look at the Python source code Python source code files use the _.py_ extension (pronounced pie). Independently, they are called called _modules_. You can group several .py files into a Python package and distribute your code using the Package Index. Here's a very simple hello.py program:
$ python ## Run the Python interpreter Python 3.4.3 (v3.4.3:9b73f1c3e601, February 24 2015) [MSC v.1600 Intel on win32] on wolf359 Type "help", "copyright", "credits" or "license" for more information. >>> r = 16 ## sets a variable in this interpreter session >>> r ## entering the expression prints its value 6 >>> r + 2 8 >>> r = 'Hello, Python' ## 'a' can also hold a string >>> r 'Hello, Python' >>> len(r) ## call the len() function on a string 13 >>> r * len(r) ## now let's break something Traceback (most recent call last): File "", line 1, in TypeError: cannot concatenate 'str' and 'int' objects >>> r + str(len(r)) ## probably what you really wanted 'Hello, Python2' >>> foobar ## this does't work either Traceback (most recent call last): File "", line 1, in NameError: name 'foobar' is not defined
Run this program from the command line looks like:
#!/usr/bin/env python # import modules import sys # Wrap code in a main() function def main(): print('Hello there', sys.argv) # call the main() function to begin # the program. if __name__ == '__main__': main()
### Importing Modules, Command-line arguments, and the len() function The outermost statements in a Python file, or module, execute the programs one-time runtime setup. Statements always run from top to bottom the first time the module is imported, setting up its variables, functions, and methods. A Python module can be run directly from the command line, like I showed above.
$ python hello.py Mary Jane Hello there Mary ## notice how the second argument drops $ ./hello.py James ## without needing 'python' first (Unix) Hello there James
python hello.py Dylan
or it can be imported and used by another Python module.
When a Python file is run directly, the special variable name is set to main.
Therefore, it's common to have the the standard
if __name__ == ...
shown above to call a main() function when the module is run directly, but not when the module is imported by some other module.
In a standard Python program, the list sys.argv contains the command-line arguments in the standard way with sys.argv being the program itself, sys.argv the first argument, etc. If you know about argc (the number of arguments), you can very easily request this value from Python with len(sys.argv), just like I demonstrated in the Python interpreter code section above when requesting the length of a string.
In general, len() can tell you how long the string (in number of characters), the number of elements in lists and tuples, and the number of key-value pairs in a standard dictionary.
Functions in Python are defined like this:
# Defines a function that takes 2 arguments (string and bang) def reminder(s, bang) ''' this is a multi-line comment in python define the string and if bang is true, return the result ''' result = s * 3 if bang: result = result + '!!!' print(result) # now call the function repeat('My String', True)
Notice how the lines that make up the function or if-statement are grouped by all having the same level of indentation. The def keyword defines the name of the function with its parameters, within parentheses and its code indented. The first line of a function can be a documentation string (docstring) that describes what the function does. The docstring can be a single line, or a multi-line description as in the example above. Docstrings are defined by triple quotes, a feature unique to Python. Variables defined in the function are local to that function, so the result in the above function is separate from a result variable in another function. The print statement takes an argument, in which case that is the value returned to the calling function.
When we run the code above, it returns:
Functions must be defined by the execution of a def keyword before they are called. It's typical to def a main() function towards the bottom of the file with all of the functions it calls stacked above it.
As I mentioned earlier, Python is heavily indented. It's a unique feature in Python. The whitespace indentation of a piece of code affects its function and meaning. A logically grouped block of statements such as the ones that make up a function should all have the same indentation, set in from the indentation of their parent function or if statement; or the code directly preceding. If one of the lines in a group has a different indentation, it will be flagged as a syntax error.
According to the official Python style guide (PEP 8), you should indent with 4 spaces. I like to use 4 spaces.
Although, apparently, Google's internal Python style guidelines dictate that Python code be indented by 2 spaces.
Code Checked at Runtime
Python does very little checking at compile time, deferring almost all types and names, checks on each line until that line runs. Suppose the above main() calls repeat() like this:
def main(): if name == 'Marko': print reminders(name) + '!!!' else: print reminder(name)
The if-statement contains an obvious typographical error, where the reminder() function is accidentally typed in as reminders(). The cool things is... Python compiles this code and runs fine so long as the name passed in at runtime is not 'Marko'. Not until a program run actually tries to execute the repeeeet(name) code section will it notice that there is no such function and raise an error. This means that when you first run a Python program, some of the first errors you see will be simple typos like this. Some programmers believe that this is one of the advantages of more verbose languages like Java and C++. Those languages catch typos and other errors at compile time.
Since Python variables don't have any type spelled out in the source code, it's extra helpful to give meaningful names to your variables, if nothing more than to remind yourself of what's going on in your code. So, you should use name if it's a single name, and names if it's a list of names, a tuple, or a list of lists or list of tuples.
Some of the most basic Python errors result from forgetting what type of value is stored in each variable, so use a consistent naming convention when naming your variable to help you keep everything straight in your program.
As far as actual naming goes, some languages prefer underscored_parts for variable names made up of more than one word, but other languages prefer camelCasing. In general, Python prefers the underscore method but guides developers to defer to camelCasing if integrating into existing Python code that already uses that style. Readability counts. Read more in the section on naming conventions in PEP 8.
As you can guess, keywords like 'print' and 'while' cannot be used as variable names — you'll get a syntax error if you do. However, be careful not to use built-ins as variable names. For example, while 'str' and 'list' may seem like good names, you'd be overriding those system variables. Built-ins are not keywords and thus, are susceptible to inadvertent use by new Python developers.
More on Modules and their Namespaces
Let's say we have a Python module called blinkers.py which contains a function named foo(). The fully qualified name of that foo function is blinkers.foo. This way, various Python modules can name their functions and variables whatever they want, and the variable names will not conflict — that is to say, module1.foo is different from module2.foo. In the Python vocabulary, we'd say that blinkers, module1, and module2 each have their own namespaces, which as you probably already figured out are their variable-name-to-object bindings.
For example, we have the standard sys module that contains some standard system facilities, like the argv list, and exit() function. With the statement "import sys" you can can access the definitions in the sys module and makes them available by their fully-qualified name, e.g. sys.exit().
import sys # Now can refer to sys.xxx facilities sys.exit(0)
There is another import form that looks like this:
from sys import argv, exit
That makes argv and exit() available by their short names; however, it is recommended that the original form with the fully-qualified namespaces be used because it's a lot easier to determine from where a function originated.
There are currently thousands of modules and packages which are bundled with a standard installation of the Python interpreter, so you don't have do anything extra to use them. Just import the module.
These are collectively known as the Python Standard Library.
Commonly used modules/packages include:
sys — access to exit(), argv, stdin, stdout, ...
re — regular expressions
os — operating system interface, file system
The Python Standard Library modules and packages can be found at http://docs.python.org/library.
Alternatively, the Python Package Index exists for the Python user community to contribute to and extend the Standard Library.