Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in languages such as C++ or Java. The language provides constructs intended to enable clear programs on both a small and large scale.
The language Python is named after the BBC show Monty Python’s Flying Circus and has nothing to do with reptiles.
Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library.
Python was conceived in the late 1980s, and its implementation was started in December 1989 by Guido van Rossum at CWI in the Netherlands as a successor to the ABC language (itself inspired by SETL) capable of exception handling and interfacing with the Amoeba operating system. Van Rossum is Python's principal author, and his continuing central role in deciding the direction of Python is reflected in the title given to him by the Python community, benevolent dictator for life.
The core philosophy of the language is summarized by the document "PEP 20 (The Zen of Python)", which includes aphorisms such as:
Python enables programs to be written compactly and readably. Programs written in Python are typically much shorter than equivalent C, C++, or Java programs, for several reasons:
Python is extensible: if you know how to program in C it is easy to add a new built-in function or module to the interpreter, either to perform critical operations at maximum speed, or to link Python programs to libraries that may only be available in binary form (such as a vendor-specific graphics library). Once you are really hooked, you can link the Python interpreter into an application written in C and use it as an extension or command language for that application.
On Linux machine, Python is usually installed by default. To install Python on other systems, check out the Python Setup and Usage section in Python help documentation.
The Python interpreter is usually installed as
/usr/bin/python on those machines where it is available.
To start a Python interpreter, type the command in your terminal:
To terminate the Python interpreter, type an end-of-file character (
Control-D on Unix,
Control-Z on Windows) at the primary prompt. If that doesn’t work, you can exit the interpreter by typing the following command:
fli@carbon:~$ python Python 2.7.9 (default, Mar 1 2015, 12:57:24) [GCC 4.9.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> exit()
Write down your Python script and name it as
Your script contents look like this
#!/usr/bin/python print('Hello World')
Go to your terminal, make your script executable
chmod +x hello.py
Run the script in your terminal
Note The line
#!/usr/bin/python should appear at the very beginning of your file. Alternatively, you can let your environment variable to specify which Python to use as
It is possible to use encodings different than ASCII in Python source files. The best way to do it is to put one more special comment line right after the
#! line to define the source file encoding:
# -*- coding: utf-8 -*-
hello.py will be able handle more complicated texts. By using UTF-8, characters of most languages in the world can be used simultaneously in string literals and comments. Using non-ASCII characters in identifiers is not supported. To display all these characters properly, your editor must recognize that the file is UTF-8, and it must use a font that supports all the characters in the file.
IPython is a command shell for interactive computing in multiple programming languages, originally developed for the Python programming language, that offers introspection, rich media, shell syntax, tab completion, and history. IPython provides the following features:
To start iPython interactive environment, type
ipython in your terminal.
Help is available in Python sessions using
Some functions (and modules) have very long help files. When using IPython, these can be paged using the command
function? so that the text can be scrolled using page up and down and
function?? can be used to type the entire function including both the
docstring and the code.
Python has a large standard library, commonly cited as one of Python's greatest strengths, providing tools suited to many tasks. This is deliberate and has been described as a "batteries included" Python philosophy. For Internet-facing applications, a large number of standard formats and protocols are supported. Modules for creating graphical user interfaces, connecting to relational databases, pseudo random number generators, arithmetic with arbitrary precision decimals, manipulating regular expressions, and doing unit testing are also included.
Some parts of the standard library are covered by specifications, but the majority of the modules are not. They are specified by their code, internal documentation, and test suite (if supplied). However, because most of the standard library is cross-platform Python code, there are only a few modules that must be altered or completely rewritten by alternative implementations.
The standard library is not essential to run Python or embed Python within an application. Blender 2.49, for instance, omits most of the standard library.
As of August 2015, the Python Package Index, the official repository of third-party software for Python, contains more than 65,000 packages offering a wide range of functionality, including:
3 + 2
5 + 4*3
The return type of a division (/) operation depends on its operands. If both operands are of type int, floor division is performed and an int is returned. If either operand is a float, classic division is performed and a float is returned. The // operator is also provided for doing floor division no matter what the operands are.
8/5 #In Python 2, int / int -> int, you will get 1 instead of 1.6. But in Python 3 will get precise division
8/5.0 # int / float -> float
8//5.0 # explicit floor division discards the fractional part
The remainder can be calculated with the % operator
17 % 3
Note To always get precise division in Python 2, use
from __future__ import devision
With Python, it is possible to use the ** operator to calculate powers. Note Caret (^) in Python behaves differently. It invokes the exclusive OR of the object: a logical operation that outputs true only when both inputs differ (one is true, the other is false).
The equal sign (=) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:
a = 3 b = 5 c = a + b c
In interactive mode, the last printed expression is assigned to the variable _. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations.
Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes ('...') or double quotes ("...") with the same result.
LastName = "Li"
FirstName = "Feng"
\ can be used to escape quotes:
print("Hello \n World!")
If you don't want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an
r before the first quote:
print(r"Hello \n World!")
Hello \n World!
Strings can be concatenated (glued together) with the
+ operator, and repeated with
"I " + 'L' + 'o'*5 + 've' + ' you'
'I Looooove you'
The built-in function
len() returns the length of a string:
Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated. This feature is particularly useful when you want to break long strings:
print("Hi, my name is Feng Li." " And I am from Beijing.")
Hi, my name is Feng Li. And I am from Beijing.
Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:
Name = "Feng Li" Name
In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain a substring:
However, out of range slice indexes are handled gracefully when used for slicing:
Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.
values = [1,5,7,9,12]
Lists also supports operations like concatenation:
values + ["22","33"]
[1, 5, 7, 9, 12, '22', '33']
Lists are a mutable type, i.e. it is possible to change their content:
values = [1,2,3,4,67,22] values
[1, 2, 3, 4, 67, 22]
values = 1000 values
[1, 2, 1000, 4, 67, 22]
You can also add new items at the end of the list, by using the append() method
[1, 2, 1000, 4, 67, 22, 9999]
Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:
values[2:4] = [2,3,4] values
[1, 2, 2, 3, 4, 67, 22, 9999]
values[:] =  values len(values)
The Python interpreter has a number of functions built into it that are always available. They are listed here in alphabetical order. Use e.g.
help(abs) to see the function help.
abs() divmod() input() open() staticmethod() all() enumerate() int() ord() str() any() eval() isinstance() pow() sum() basestring() execfile() issubclass() print() super() bin() file() iter() property() tuple() bool() filter() len() range() type() bytearray() float() list() raw_input() unichr() callable() format() locals() reduce() unicode() chr() frozenset() long() reload() vars() classmethod() getattr() map() repr() xrange() cmp() globals() max() reversed() zip() compile() hasattr() memoryview() round() __import__() complex() hash() min() set() apply() delattr() help() next() setattr() buffer() dict() hex() object() slice() coerce() dir() id() oct() sorted() intern()
Then you can use all the mathematical functions inside
math module as:
Alternatively, you can do the following changes
import math as mt mt.exp(1)
If you just want to import one or two functions from a module
from math import exp exp(3)
from math import exp as myexp myexp(1)
x = -3 if x < 0: x = 0 print('Negative changed to zero') elif x == 0: print('Zero') elif x == 1: print('Single') else: print('More')
Negative changed to zero
words = ['cat', 'window', 'defenestrate'] for w in words: print(w, len(w))
cat 3 window 6 defenestrate 12
We can create a function that writes the Fibonacci series to an arbitrary boundary.
The first line should always be a short, concise summary of the object's purpose. For brevity, it should not explicitly state the object's name or type, since these are available by other means (except if the name happens to be a verb describing a function's operation). This line should begin with a capital letter and end with a period.
If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description. The following lines should be one or more paragraphs describing the object's calling conventions, its side effects, etc.
The first statement of the function body can optionally be a string literal; this string literal is the function’s documentation string, or docstring. There are tools which use docstrings to automatically produce online or printed documentation, or to let the user interactively browse through code; it's good practice to include docstrings in code that you write, so make a habit of it.
def fib(n): # write Fibonacci series up to n """Print a Fibonacci series up to n.""" # the function help a, b = 0, 1 while a < n: print(a) a, b = b, a+b
Help on function fib in module __main__: fib(n) Print a Fibonacci series up to n.
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while True: ok = input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries < 0: raise IOError('refusenik user') print(complaint)
raw_input() only works with Python 2. To make it it work with Python 3, change
return statement returns with a value from a function. return without an expression argument returns None. Falling off the end of a function also returns None.
ask_ok("Do you really want to go?")
Do you really want to go?yes
Small anonymous functions can be created with the
lambda keyword. Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope. The example uses a lambda expression to return a function
def make_incrementor(n): return lambda x: x + n f = make_incrementor(42)
Use 4-space indentation, and no tabs. 4 spaces are a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read). Tabs introduce confusion, and are best left out.
Wrap lines so that they don't exceed 79 characters. This helps users with small displays and makes it possible to have several code files side-by-side on larger displays.
Use blank lines to separate functions and classes, and larger blocks of code inside functions.
When possible, put comments on a line of their own.
Use spaces around operators and after commas, but not directly inside bracketing constructs:
a = f(1, 2) + g(3, 4).
Name your classes and functions consistently; the convention is to use CamelCase for classes and lower_case_with_underscores for functions and methods. Always use
self as the name for the first method argument (see A First Look at Classes for more on classes and methods).
Don’t use fancy encodings if your code is meant to be used in international environments. Plain ASCII works best in any case.