Skip to content
Search

Python:Basic

lastmod 2019-03-22created 2015-03-1014 edits

INTRO TIP

If you're not sure, use it as shown below.

a = 1
help(a)
## OR
dir(a)
## OR
import inspect
inspect.getmembers(a, predicate=inspect.ismethod)

To check the class (Type), use the following.

a = 1
a.__class__

To compare classes (Types), use isinstance.

isinstance(x, int)
isinstance(x, basestring) # Python 2.x, you would do
isinstance(x, str) # In Python 3.x, it would be
isinstance(x, unicode) # In Python 3.x, it would be
isinstance(x, list)

To check whether an object has an attribute, use hasattr.

hasattr(a, "imag")

Operator

The following operators are unusual compared to other popular programming languages1. The // operator discards the digits after the decimal point.

7 / 5.0 # 1.4
7 // 5.0 # 1.0

** is exponentiation.

3 ** 3 # 27
5 ** 2 # 25

Boolean Operations

Python has no && or ||. Use and and or respectively, and not for negation (!).

Note that == does exist, and it differs from is.

  • ==: compares values.
  • is: compares references.

See here for details.

Arrays

For loop inside an array

Used as below, you can add data through a For loop.

list1 = [ "main", "test" ]
list2 = [i for i in list1]

You can also extend it as below.

list2 = [i.split("a") for i in list1]

Read it from the right. Each element of list1 is stored in the variable i, and each i string is split on "a".

You can also add a condition as below.

nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print even_squares  # Prints "[0, 4, 16]"

with

with is a feature introduced in Python 2.5. By defining __enter__() and __exit__(), which are executed by the specified object (context manager), it can replace the code that runs before and after the body of a with statement.

A with statement can be used in place of try/finally, more simply and easily.

with A:
    pass

In the code above, A calls A.enter() when the with block starts and A.exit() when the block ends. Even if an exception occurs inside the block, stopping its execution and exiting it, A.exit() is guaranteed to be called.

Example

with open('filename','w') as f:
    f.write(someString);

ForLoop

for x in range(0, 3):
    print "We're on time %d" % (x)

Yield

def my_range(start, end, step):
    while start <= end:
        yield start
        start += step

for x in my_range(1, 10, 0.5):
    print x

See also

Favorite site

References


  1. For example, C/C++, Java, etc ↩

author Zer0 sitemap