Python:Basic
lastmod 2019-03-22created 2015-03-1014 edits
INTRO TIP
If you're not sure, use it as shown below.
To check the class (Type), use the following.
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.
Operator
The following operators are unusual compared to other popular programming languages1. The // operator discards the digits after the decimal point.
** is exponentiation.
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.
You can also extend it as below.
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
- Understanding Python's "with" statement
- The Python with statement
- Understanding the Python with statement and context managers
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.
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
ForLoop
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
- [Recommended] 5. Built-in Types