Hello, World
Python is a high-level, structured, open-source, dynamically typed programming language that can be used for a wide variety of programming tasks.
Two major versions of Python are currently in active use:
- Python 2.x is the legacy language
- Python 3.x is the current language and is under active development
You can download and install the latest version of Python 2 or Python 3 at the official website. See Python 2 vs. Python 3 for more info on differences between both versions. In addition, a number of providers offer re-packed versions of Python that add commonly used libraries and other features to ease setup for common uses—such as math, data-intensive or scientific use. See the list at the official website.
Hello World Python file
Create a new file hello.py
containing the following line:
print('Hello World')
If using Python 2, you may also type the line below. Note that this is not valid in Python 3 and thus not recommended as it reduces cross-version code compatibility.
print 'Hello World'
Execute with Python
Verify that you have Python installed by running the following command in your favorite terminal (eg. cmd prompt, LXTerminal):
$ python --version
If you have Python 2 installed, and it is your default Python (see Troubleshooting for more details) you should see something like this:
$ python --version
Python 2.7.9
If you have Python 3 installed, and it is your default Python (again, see Troubleshooting for more details) you should see something like this:
$ python --version
Python 3.5.2
In the command prompt, navigate to the directory containing the file hello.py
.
For those who aren't familiar with the terminal, use cd <dir>
to change directories. Windows users can also Shift-right-click and select Open command window here
in a folder where hello.py
is contained. MacOS users can drag any folder from a Finder window into the terminal to copy the path to that folder.
Type python hello.py
, then hit the Enter key.
$ python hello.py
Hello World
You can also substitute hello.py
with the path to your file. For example, if you have the file in your home directory and your user is "user" on Linux, you can type python /home/user/hello.py
.
You should see "Hello World" printed to the console.
"Hello World" one liner
You can also print "Hello World" in terminal by following way:
$ python3 -c 'print('Hello World')'
Hello World
Launch Interactive Python Shell
Just by executing python
command in your terminal, you can swap into Interactive Python Shell:
$ python
Python 2.7.12 (default, Jul 1 2016, 15:12:24)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print('Hello World')
Hello World
>>>
Interactive Python Shell is a very practical tool for learning and testing the features of the Python language while playing with the values and syntax interactively. Currently most of the system's default Python Interpreter is Python 2.x, so execute python3
command if you want to use Interactive Shell with Python 3.x Interpreter.
Try Interactive Python Shell Online.
Common guidelines for python coding standards are specified in PEP8 specs.
Creating variables and assigning values
To create a variable in Python, all you need to do is specify the variable name, and then assign a value to it. Python uses =
to assign values to variables. There's no need to declare a variable in advance (or to assign a data type to it), assigning a value to a variable itself declares and initiates the variable with that initial value. So you can not declare a variable without an initial value.
a = 2
print(a)
# Out: 2
b = 9223372036854775807
print(b)
# Out: 9223372036854775807
pi = 3.14
print(pi)
# Out: 3.14
c = 'A'
print(c)
# Out: A
name = 'John Doe'
print(name)
# Out: John Doe
q = True
print(q)
# Out: True
x = None
print(x)
# Out: None
Even though there's no need to specify a data type when declaring a variable in Python, while allocating the necessary area in memory for the variable, Python Interpreter automatically picks the most suitable built-in type for it:
a = 2
print(type(a))
# Out: <type 'int'>
b = 9223372036854775807
print(type(b))
# Out: <type 'int'>
pi = 3.14
print(type(pi))
# Out: <type 'float'>
c = 'A'
print(type(c))
# Out: <type 'str'>
name = 'John Doe'
print(type(name))
# Out: <type 'str'>
q = True
print(type(q))
# Out: <type 'bool'>
x = None
print(type(x))
# Out: <type 'NoneType'>
You can assign multiple values to multiple variables in one line. Note, that there must be the same number of arguments on the right and left sides of the =
operator:
a, b, c = 1, 2, 3
print(a, b, c)
# Out: 1 2 3
a, b, c = 1, 2
=> Traceback (most recent call last):
=> File "name.py", line N, in <module>
=> a, b, c = 1, 2
=> ValueError: need more than 2 values to unpack
a, b = 1, 2, 3
=> Traceback (most recent call last):
=> File "name.py", line N, in <module>
=> a, b = 1, 2, 3
=> ValueError: too many values to unpack
You can also assign a single value to several variables simultaneously.
a = b = c = 1
print(a, b, c)
# Out: 1 1 1
In this case, a
, b
, and c
, are all independent -- changing one will not change the others:
a = b = c = 1
print(a, b, c)
# Out: 1 1 1
b = 2
print(a, b, c)
# Out: 1 2 1
However, note that changing the contents of the object that is referred to by the variable will be reflected through all the others. That is, if x
and y
are mutable objects(lists, dictionaries, sets and byte arrays), changing the contents of one will be seen through the others:
x = y = [7, 8, 9] # x and y refer to the same list i.e. refer to same memory location
x = [13, 8, 9] # now we are assigning a brand new list to x (memory location for x changed!)
print(y) # y is unchanged, so it's OK
# Out: [7, 8, 9]
But:
x = y = [7, 8, 9] # x and y refer to the same list i.e. refer to same memory location
x[0] = 13 # now we are replacing first element of x with 13 (memory location for x unchanged)
print(y) # this time y changed!
# Out: [13, 8, 9]
In plain English:
x = y = [7, 8, 9] # creates hardware level bonds between x and y because [7, 8, 9] is a mutable object
x = y = 7 # does not create any bonds, just assigns because 7 is an immutable object
Lastly, Python uses duck typing, so variables do not have to stay the same type as which they were first defined -- you can simply use =
to assign a new value to a variable, even if that value is of a different type.
a = 2
print(a)
# Out: 2
a = "New value"
print(a)
# Out: New value
Block Indentation
First of all, unlike the other popular programming languages (except CoffeScript, Haskell etc.), indentation in Python is mandatory. Because indentation's itself seamlessly defines the code blocks and with this Python aims to be more human-readable. Despite that, this rule can cause you some troubles if your code editor is miscalibrated.
Python uses the colon symbol (:
) and indentation for showing where blocks of code begin and end (If you come from another language, do not confuse this with somehow being related to the ternary operator). That is, blocks in Python, such as functions, loops, if
clauses and other constructs, have no ending identifiers. All blocks start with a colon and then contain the indented lines below it.
For example:
def my_function(): # This is a function definition. Note the colon (:)
a = 2 # This line belongs to the function because it's indented
return a # This line also belongs to the same function
print(my_function()) # This line is OUTSIDE the function block
or
if a > b: # If block starts here
print(a) # This is part of the if block
else: # else must be at the same level as if
print(b) # This line is part of the else block
Blocks that contain exactly one single-line statement may be put on the same line, though this form is generally not considered good style:
if a > b: print(a)
else: print(b)
Attempting to do this with more than a single statement will not work:
if x > y: y = x
print(y) # IndentationError: unexpected indent
if x > y: while y != z: y -= 1 # SyntaxError: invalid syntax
An empty block causes an IndentationError
. Use pass
(a command that does nothing) when you have a block with no content:
def will_be_implemented_later():
pass
Spaces vs. Tabs
In short: always use 4 spaces for indentation.
Using tabs exclusively is possible but PEP 8, the style guide for Python code, states that spaces are preferred.
Python 3 disallows mixing the use of tabs and spaces for indentation. In such case a compile-time error is generated: Inconsistent use of tabs and spaces in indentation
and the program will not run.
Python 2 allows mixing tabs and spaces in indentation; this is strongly discouraged. The tab character completes the previous indentation to be a multiple of 8 spaces. Since it is common that editors are configured to show tabs as multiple of 4 spaces, this can cause subtle bugs.
Citing PEP 8:
When invoking the Python 2 command line interpreter with the
-t
option, it issues warnings about code that illegally mixes tabs and spaces. When using-tt
these warnings become errors. These options are highly recommended!
Many editors have "tabs to spaces" configuration. When configuring the editor, one should differentiate between the tab character ('\t') and the Tab key.
- The tab character should be configured to show 8 spaces, to match the language semantics - at least in cases when (accidental) mixed indentation is possible. Editors can also automatically convert the tab character to spaces.
- However, it might be helpful to configure the editor so that pressing the Tab key will insert 4 spaces, instead of inserting a tab character.
Python source code written with a mix of tabs and spaces, or with non-standard number of indentation spaces can be made pep8-conformant using autopep8. (A less powerful alternative comes with most Python installations: reindent.py)
IDLE - Python GUI
IDLE is Python’s Integrated Development and Learning Environment and is an alternative to the command line. As the name may imply, IDLE is very useful for developing new code or learning python. On Windows this comes with the Python interpreter, but in other operating systems you may need to install it through your package manager.
In IDLE, hit F5
or run Python Shell
to launch an interpreter. Using IDLE can be a better learning experience for new users because code is interpreted as the user writes.
Troubleshooting
-
Windows
If you're on Windows, the default command is
python
. If you receive a"'python' is not recognized"
error, the most likely cause is that Python's location is not in your system'sPATH
environment variable. This can be accessed by right-clicking on 'My Computer' and selecting 'Properties' or by navigating to 'System' through 'Control Panel'. Click on 'Advanced system settings' and then 'Environment Variables...'. Edit thePATH
variable to include the directory of your Python installation, as well as the Script folder (usuallyC:\Python27;C:\Python27\Scripts
). This requires administrative privileges and may require a restart.When using multiple versions of Python on the same machine, a possible solution is to rename one of the
python.exe
files. For example, naming one versionpython27.exe
would causepython27
to become the Python command for that version.You can also use the Python Launcher for Windows, which is available through the installer and comes by default. It allows you to select the version of Python to run by using
py -[x.y]
instead ofpython[x.y]
. You can use the latest version of Python 2 by running scripts withpy -2
and the latest version of Python 3 by running scripts withpy -3
.
-
Debian/Ubuntu/MacOS
This section assumes that the location of the
python
executable has been added to thePATH
environment variable.If you're on Debian/Ubuntu/MacOS, open the terminal and type
python
for Python 2.x orpython3
for Python 3.x.Type
which python
to see which Python interpreter will be used.
-
Arch Linux
The default Python on Arch Linux (and descendants) is Python 3, so use
python
orpython3
for Python 3.x andpython2
for Python 2.x.
-
Other systems
Python 3 is sometimes bound to
python
instead ofpython3
. To use Python 2 on these systems where it is installed, you can usepython2
.
Datatypes
Built-in Types
Booleans
bool
: A boolean value us eitherTrue
orFalse
.
Numbers
-
int
: Integer numbera = 2 b = 100 c = 123456789
Note: in older versions of Python, a
long
type was available and this was distinct fromint
. The two have been unified. -
float
: Floating point number; precision depends on the implementation and system architecture, for Cpython the Float datatype corresponds to a C double.a = 2.0 b = 100.e0 c = 123456789.e1
-
complex
: Complex numbersa = 2 + 1j b = 100 + 10j
Sequences and collections
Python differentiates between ordered sequences and unordered collections (such as set
and dict
).
-
str
: Character string; in Python 3 it is aunicode
string, while in Python 2 it is a byte string. -
unicode
: In Python 3 this type does not exist,str
replaces; in Python 2 it represents anunicode
encoded string. -
bytes
: In Python 3 this represents a string of bytes, without encoding defined; in Python 2 this is a synonym ofstr
. -
tuple
: An ordered collection ofn
values of any type (n >= 0
); supports indexing; immutable; hashable if all its members are hashable.a = (1, 2, 3) b = ('a', 1, 'python', (1, 2)) b[2] = 'something else' # returns an error
-
list
: An ordered collection ofn
values (n >= 0
); not hashable; mutable.a = [1, 2, 3] b = ['a', 1, 'python', (1, 2), [1, 2]] b[2] = 'something else' # allowed
-
set
: An unordered collection of unique values.a = {1, 2, 'a'}
-
dict
: An unordered collection of unique key-value pairs; keys must be hashable.An object is hashable if it has a hash value which never changes during its lifetime (it needs a
__hash__()
method), and can be compared to other objects (it needs an__eq__()
method). Hashable objects which compare equal must have the same hash value.a = {1: 'one', 2: 'two'} b = {'a': [1, 2, 3], 'b': 'a string'}
Built-in constants
In conjunction with the built-in datatypes there are a small number of built-in constants in the built-in namespace:
True
: The true value of the built-in typebool
False
: The false value of the built-in typebool
None
: A singleton object used to signal that a value is absent.Ellipsis
or...
: not used in core Python itself butnumpy
and related packages use this as a 'include everything' reference in arrays.NotImplemented
: a singleton used to indicate to Python that a special method doesn't support the specific arguments, and Python will try alternatives if available.
a = None # No value will be assigned. Any valid datatype can be assigned later
None
doesn't have any natural ordering. Using ordering comparison operators (<
, <=
, >=
, >
) isn't supported anymore and will raise a TypeError
.
None
is always less than any number (None < -32 evaluates to
True`).
Testing the type of variables
In python, we can check the datatype of an object using the built-in function type
.
a = '123'
print(type(a))
#Out: <class 'str'>
b = 123
print(type(b))
#Out: <class 'int'>
In conditional statements it is possible to test the datatype with isinstance
. However, it is usually not encouraged to rely on the type of the variable.
i = 7
if isinstance(i, int):
i += 1
elif isinstance(i, str):
i = int(i)
i += 1
For information on the differences between type()
and isinstance()
read: Differences between isinstance and type in Python
To test if something is of NoneType
:
x = None
if x is None:
print('Not a surprise, I just defined x as None.')
Converting between datatypes
You can perform explicit datatype conversion.
For example, '123' is of str
type and it can be converted to integer using int
function.
a = '123'
b = int(a)
Converting from a float string such as '123.456' can be done using float
function.
a = '123.456'
b = float(a)
You can also convert sequence or collection types
a = 'hello'
list(a) # returns ['h', 'e', 'l', 'l', 'o']
set(a) # returns {'o', 'e', 'l', 'h'}
Explicit string type at definition of literals
With one letter labels just in front of the quotes you can tell what type of string you want to define.
b'foo bar'
: resultsbytes
in Python 3,str
in Python 2u'foo bar'
: resultsstr
in Python 3,unicode
in Python 2'foo bar'
: resultsstr
r'foo bar'
: results so called raw string, where escaping special characters is not necessary, everything is taken verbatim as you typed
To see how raw string makes a difference, try this:
normal = 'foo\nbar'
escaped = 'foo\\nbar'
raw = r'foo\nbar'
print(normal)
# Out: foo
# bar
print(escaped)
# Out: foo\nbar
print(raw)
# Out: foo\nbar
Datatype related exceptions (errors)
If the original value is not valid value for target type, then a ValueError
exception will be raised.
int('a')
'''
Out: Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a'
'''
This method is a simple solution for example if you want to the user input (which, in Python 3, is always str
) to a number:
value = int(input()) # Read user input and convert to integer
(However, in a real application, not a bad idea to add some checking and error handling.)
User Input
Interactive input
To get input from the user, use the input
function (note: in Python 2.x, the function is called raw_input
instead, although Python 2.x has its own version of input
that is completely different):
name = raw_input("What is your name? ")
# Out: What is your name? _
Security Remark Do not use
input()
in Python2 - the entered text is will be evaluated as if it were a Python expression (equivalent toeval(input())
in Python3), which might easily become a vulnerability. See this article for further information on the risks of using this function.
name = input("What is your name? ")
# Out: What is your name? _
The remainder of this example will be using Python 3 syntax.
The function takes a string argument, which it displays as a prompt, and returns a string. The above provides a prompt, waiting for me to type my name in:
name = input("What is your name? ")
# Out: What is your name?
If I type "Bob" and hit enter, now the variable name
contains the string "Bob"
:
name = input("What is your name? ")
# Out: What is your name? Bob
print(name)
# Out: Bob
Note that the input
is always of type str
, which is important if you want the user to enter numbers. Therefore, you need to convert the str
before trying to use it as a number:
x = input("Write a number:")
# Out: Write a number: 10
x / 2
# Out: TypeError: unsupported operand type(s) for /: 'str' and 'int'
float(x) / 2
# Out: 5.0
NB: It's recommended to use try
/except
blocks to catch exceptions when dealing with user inputs. For instance, if your code wants to cast a raw_input
into an int
, and what the user writes is uncastable, it raises a ValueError
.
Collection Types
Lists
There are a number of collection types in Python. While types such as int
and str
hold a single value, collection types hold multiple values.
The list
type is probably the most commonly used collection type in Python. Despite its name, a list is more like an array in other languages, mostly JavaScript. In Python, a list is merely a ordered collection of valid Python values. The values are not restricted to a single data type, which makes sense given Python is a dynamic language. Lists are also variable length, so you can add and remove values. They are also mutable, so you can change the values in a list. A list can be created by enclosing values, separated by commas, in square brackets:
my_list = [1, 2, 3, 'a', 'b', 'c', True, False, None, ['another', 'list'], []]
As you can see, lists can be nested and can also be empty. The elements of a list can be accessed via an index, or numeric representation of their position. Lists in Python are zero-indexed meaning that the first element in the list is at index 0, the second element is at index 1 and so on. Indices can also be negative which which start at the end of the list. So:
last_element = my_list[-1]
Would return the last element in the above list which is the empty list: []
.
You can iterate over the list elements like below
for element in my_list:
print (element)
Tuples
A tuple
is similar to a list except that is it fixed-length and immutable. So the values in the tuple cannot be changed nor the values be added to or removed from the tuple. Tuples are commonly used for small collections of values that will not need to change, such as an IP address and port. Tuples are represented with parentheses instead of square brackets:
ip_address = ('10.20.30.40', 8080)
The same indexing rules for lists also apply to tuples. Tuples can also be nested and the values can be any valid Python valid.
A tuple with only one member must be defined (note the comma) this way:
one_member_tuple = ('Only member',)
or
one_member_tuple = 'Only member', # No brackets
or just using tuple
syntax
one_member_tuple = tuple(['Only member'])
Dictionaries
A dictionary
in Python is a collection of key-value pairs. The dictionary is surrounded by curly braces. Each pair is separated by a comma and the key and value are separated by a colon. Here is an example:
state_capitols = {
'Arkanasas': 'Little Rock',
'Colorado': 'Denver',
'California': 'Sacremento',
'Georgia': 'Atlanta'
}
To get a value, refer to it by its key:
ca_capitol = state_capitols['California']
You can also get all of the keys in a dictionary and then iterate over them:
for k in state_capitols.keys():
print('{} is the capitol of {}'.format(state_capitol[k], k))
If dictionaries remind you of JSON, you're not dreaming! The native json
module in the Python standard library converts between JSON and dictionaries. In fact, JSON is one of the most common uses of dictionaries.
defaultdict
A defaultdict
is a dictionary with a default value for keys, so that keys for which no value has been explicitly defined can be accessed without errors. defaultdict
is especially useful when the values in the dictionary are collections(lists, dicts etc) in the sense that it doesnt need to be initialized everytime when a new key is used.
A defaultdict
will never raise a KeyError. Any key that does not exist gets the default value returned.
For example, consider the following dictionary
>>> state_capitols = {
'Arkanasas': 'Little Rock',
'Colorado': 'Denver',
'California': 'Sacremento',
'Georgia': 'Atlanta'
}
If we try to access a non-existent key, python returns us an error as follows
>>> state_capitols['Alabama']
Traceback (most recent call last):
File "<ipython-input-61-236329695e6f>", line 1, in <module>
state_capitols['Alabama']
KeyError: 'Alabama'
Let us try with a defaultdict
. It can be found in the collections module.
>>> from collections import defaultdict
>>> state_capitols = defaultdict(lambda: 'Boston')
What we did here is to set a default value (Boston) incase the give key doesnt exist. let us try to populate the dict as before
>>> state_capitols['Arkanasas'] = 'Little Rock'
>>> state_capitols['California'] = 'Sacremento'
>>> state_capitols['Colorado'] = 'Denver'
>>> state_capitols['Georgia'] = 'Atlanta'
If we try to access the dict with a non-existent key, python will return us the default value i.e. Boston
>>> state_capitols['Alabama']
'Boston'
and returns the created values for existing key just like a normal dictionary
>>> state_capitols['Arkanasas']
'Little Rock'
Built in Modules and Functions
A module is a file containing Python definitions and statements. Function is a piece of code which execute some logic.
>>> pow(2,3)
8
To check the built in function in python
>>> dir(__builtins__)
[
'ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'BufferError',
'BytesWarning',
'DeprecationWarning',
'EOFError',
'Ellipsis',
'EnvironmentError',
'Exception',
'False',
'FloatingPointError',
'FutureWarning',
'GeneratorExit',
'IOError',
'ImportError',
'ImportWarning',
'IndentationError',
'IndexError',
'KeyError',
'KeyboardInterrupt',
'LookupError',
'MemoryError',
'NameError',
'None',
'NotImplemented',
'NotImplementedError',
'OSError',
'OverflowError',
'PendingDeprecationWarning',
'ReferenceError',
'RuntimeError',
'RuntimeWarning',
'StandardError',
'StopIteration',
'SyntaxError',
'SyntaxWarning',
'SystemError',
'SystemExit',
'TabError',
'True',
'TypeError',
'UnboundLocalError',
'UnicodeDecodeError',
'UnicodeEncodeError',
'UnicodeError',
'UnicodeTranslateError',
'UnicodeWarning',
'UserWarning',
'ValueError',
'Warning',
'ZeroDivisionError',
'__debug__',
'__doc__',
'__import__',
'__name__',
'__package__',
'abs',
'all',
'any',
'apply',
'basestring',
'bin',
'bool',
'buffer',
'bytearray',
'bytes',
'callable',
'chr',
'classmethod',
'cmp',
'coerce',
'compile',
'complex',
'copyright',
'credits',
'delattr',
'dict',
'dir',
'divmod',
'enumerate',
'eval',
'execfile',
'exit',
'file',
'filter',
'float',
'format',
'frozenset',
'getattr',
'globals',
'hasattr',
'hash',
'help',
'hex',
'id',
'input',
'int',
'intern',
'isinstance',
'issubclass',
'iter',
'len',
'license',
'list',
'locals',
'long',
'map',
'max',
'memoryview',
'min',
'next',
'object',
'oct',
'open',
'ord',
'pow',
'print',
'property',
'quit',
'range',
'raw_input',
'reduce',
'reload',
'repr',
'reversed',
'round',
'set',
'setattr',
'slice',
'sorted',
'staticmethod',
'str',
'sum',
'super',
'tuple',
'type',
'unichr',
'unicode',
'vars',
'xrange',
'zip'
]
To know the functionality of any function, we can use built in function help
.
>>> help(max)
Help on built-in function max in module __builtin__:
max(...)
max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.
Built in modules contains extra functionalities.For example to get square of a number we need to include math
module.
>>> import math
>>> math.sqrt(16) #to get the square root of number we use 'sqrt'
4.0
Creating a module
A module is an importable file containing definitions and statements.
A module can be created by creating a .py
file.
# hello.py
def say_hello():
print("Hello!")
Functions in a module can be used by importing the module.
$ python
>>> import hello
>>> hello.say_hello()
=> "Hello!"
Modules can be imported by other modules.
# greet.py
import hello
hello.say_hello()
Specific functions of a module can be imported.
# greet.py
from hello import say_hello
say_hello()
Modules can be aliased.
# greet.py
import hello as ai
ai.say_hello()
A module can be stand-alone runnable script.
# run_hello.py
if __name__ == '__main__':
import hello
Run it!
$ python run_hello.py
=> "Hello!"
List the identifiers that an object defines
The identifiers of the built-in function dir()
are the functions, classes and variables defined in that object. The dir()
function returns a list of strings.
If called without an argument, return the names in the current scope.
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> import os
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'os']
Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it.
>>> dir(os)
['EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST', 'EX_NOINPUT','EX_NOPERM', 'EX_NOUSER', 'EX_OK', 'EX_OSERR', 'EX_OSFILE', 'EX_PROTOCOL', 'EX_SOFTWARE', 'EX_TEMPFAIL', 'EX_UNAVAILABLE', 'EX_USAGE', 'F_OK', 'NGROUPS_MAX', 'O_APPEND', 'O_ASYNC', 'O_CREAT', 'O_DIRECT', 'O_DIRECTORY', 'O_DSYNC', 'O_EXCL', 'O_LARGEFILE', 'O_NDELAY', 'O_NOATIME', 'O_NOCTTY', 'O_NOFOLLOW', 'O_NONBLOCK', 'O_RDONLY', 'O_RDWR', 'O_RSYNC', 'O_SYNC', 'O_TRUNC', 'O_WRONLY', 'P_NOWAIT', 'P_NOWAITO', 'P_WAIT', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'ST_APPEND', 'ST_MANDLOCK', 'ST_NOATIME', 'ST_NODEV', 'ST_NODIRATIME', 'ST_NOEXEC', 'ST_NOSUID', 'ST_RDONLY', 'ST_RELATIME', 'ST_SYNCHRONOUS', 'ST_WRITE', 'TMP_MAX', 'UserDict', 'WCONTINUED', 'WCOREDUMP', 'WEXITSTATUS', 'WIFCONTINUED', 'WIFEXITED', 'WIFSIGNALED', 'WIFSTOPPED', 'WNOHANG', 'WSTOPSIG', 'WTERMSIG', 'WUNTRACED', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_copy_reg', '_execvpe', '_exists', '_exit', '_get_exports_list', '_make_stat_result', '_make_statvfs_result', '_pickle_stat_result', '_pickle_statvfs_result', '_spawnvef', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'chown', 'chroot', 'close', 'closerange', 'confstr', 'confstr_names', 'ctermid', 'curdir', 'defpath', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fchdir', 'fchmod', 'fchown', 'fdatasync', 'fdopen', 'fork', 'forkpty', 'fpathconf', 'fstat', 'fstatvfs', 'fsync', 'ftruncate', 'getcwd', 'getcwdu', 'getegid', 'getenv', 'geteuid', 'getgid', 'getgroups', 'getloadavg', 'getlogin', 'getpgid', 'getpgrp', 'getpid', 'getppid', 'getresgid', 'getresuid', 'getsid', 'getuid', 'initgroups', 'isatty', 'kill', 'killpg', 'lchown', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'major', 'makedev', 'makedirs', 'minor', 'mkdir', 'mkfifo', 'mknod', 'name', 'nice', 'open', 'openpty', 'pardir', 'path', 'pathconf', 'pathconf_names', 'pathsep', 'pipe', 'popen', 'popen2', 'popen3', 'popen4', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'rmdir', 'sep', 'setegid', 'seteuid', 'setgid', 'setgroups', 'setpgid', 'setpgrp', 'setregid', 'setresgid', 'setresuid', 'setreuid', 'setsid', 'setuid', 'spawnl', 'spawnle', 'spawnlp', 'spawnlpe', 'spawnv', 'spawnve', 'spawnvp', 'spawnvpe', 'stat', 'stat_float_times', 'stat_result', 'statvfs', 'statvfs_result', 'strerror', 'symlink', 'sys', 'sysconf', 'sysconf_names', 'system', 'tcgetpgrp', 'tcsetpgrp', 'tempnam', 'times', 'tmpfile', 'tmpnam', 'ttyname', 'umask', 'uname', 'unlink', 'unsetenv', 'urandom', 'utime', 'wait', 'wait3', 'wait4', 'waitpid', 'walk', 'write']
If the object supplies a method named __dir__, it will be used;
>>> os.__dir__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Otherwise the default dir() logic is used and returns:
- For a module object: the module's attributes.
>>> dir(os)
- For a class object: its attributes, and recursively the attributes of its bases.
>>> dir(dict)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
- For any other object: its attributes, its class's attributes, and recursively the attributes of its class's base classes.
>>> class MyClassObject(object):
... pass
...
>>> dir(MyClassObject)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
Requesting a subidentifier:
>>> dir(os.close)
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
Installation of Python 2.7.x and 3.x
Note: Following instructions are written for Python 2.7 (unless specified): instructions for Python 3.x are similar.
WINDOWS
First, download the latest version of Python 2.7 from the official Website (https://www.python.org/downloads/). Version is provided as an MSI package. To install it manually, just double-click the file.
By default, Python installs to a directory:
C:\Python27\
Warning: installation does not automatically modify the PATH environment variable.
Assuming that your Python installation is in C:\Python27, add this to your PATH:
C:\Python27\;C:\Python27\Scripts\
Now to check if Python installation is valid write in cmd:
python --version
LINUX
The latest versions of CentOS, Fedora, Redhat Enterprise (RHEL) and Ubuntu come with Python 2.7.
To install Python 2.7 on linux manually, just do the following in terminal:
wget --no-check-certificate https://www.python.org/ftp/python/2.7.X/Python-2.7.X.tgz
tar -xzf Python-2.7.X.tgz
cd Python-2.7.X
./configure
make
sudo make install
Also add the path of new python in PATH environment variable. If new python is in /root/python-2.7.X then run "export PATH = $PATH:/root/python-2.7.X"
Now to check if Python installation is valid write in terminal:
python --version
macOS
As we speak, macOS comes installed with Python 2.7.10, but this version is outdated and slightly modified from the regular Python.
The version of Python that ships with OS X is great for learning but it’s not good for development. The version shipped with OS X may be out of date from the official current Python release, which is considered the stable production version. (source)
Install Homebrew:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Install Python 2.7:
brew install python
For Python 3.x, use the command brew install python3
instead.
String function - str() and repr()
These two functions can be used to obtain a readable representation of an object.
In-short:
repr(x)
returns x.__repr__()
: representation of x
. Usually eval will convert it back to that object.
str(x)
returns x.__str__()
: whatever you think is that object in a human-readable text form.
str()
For strings, this returns the string itself. The difference with repr(object)
is that str(object)
does not always attempt to return a string that is acceptable to eval()
; its goal is to return a printable string. If no argument is given, returns the empty string, ''
.
repr()
For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval()
, otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object.
Example 1:
s = """w'o"w"""
repr(s) # Output: '\'w\\\'o"w\''
str(s) # Output: 'w\'o"w'
eval(str(s)) == s # Gives a SyntaxError
eval(repr(s)) == s # Output: True
Example 2:
import datetime
today = datetime.datetime.now()
str(today) # Output: '2016-09-15 06:58:46.915000'
repr(today) # Output: 'datetime.datetime(2016, 9, 15, 6, 58, 46, 915000)'
Help Utility
Python has several functions built into the interpreter. If you want to get information of keywords, built-in functions, modules or topics open a Python console and enter:
>>> help()
You will receive information by entering keywords directly:
>>> help(help)
or within the utility:
help> help
which will show an explanation:
Help on _Helper in module _sitebuiltins object:
class _Helper(builtins.object)
| Define the builtin 'help'.
|
| This is a wrapper around pydoc.help that provides a helpful message
| when 'help' is typed at the Python interactive prompt.
|
| Calling help() at the Python prompt starts an interactive help session.
| Calling help(thing) prints help for the python object 'thing'.
|
| Methods defined here:
|
| __call__(self, *args, **kwds)
|
| __repr__(self)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
You can also request subclasses of modules:
help(pymysql.connections)
Close the helper with 'quit'
Installing external modules using pip
pip
is your friend when you need to install any package from the plethora of choices available at the python package index (PyPI). pip
is already installed if you're using Python 2 >= 2.7.9 or Python 3 >= 3.4 downloaded from python.org. For computers running Linux or another *Nix with a native package manager, pip
must often be manually installed.
On instances with both Python 2 and Python 3 installed, pip
often refers to Python 2 and pip3
to Python 3. Using pip
will only install packages for Python 2 and pip3
will only install packages for Python 3.
Installing a package is a simple as typing
$ pip install [package_name] # latest version of the package
$ pip install [package_name]==x.x.x # specific version of the package
$ pip install '[package_name]>=x.x.x' # minimum version of the package
where x.x.x
is the version number of the package you want to install.
You can upgrade your existing pip installation by using the following commands
On Linux or OS X: pip install -U pip
You may need to use sudo
with pip on some Linux Systems
On Windows: py -m pip install -U pip
or python -m pip install -U pip
For more information regarding pip do read here.
Sign up or log in
Save edit as a guest
Join Stack Overflow
We recognize you from another Stack Exchange Network site!
Join and Save Draft