import this
The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
print("Hello World!")
Hello World!
Python programs can be decomposed into modules, statements, expressions, and objects, as follows:
Objects and operators are combined to form expressions. Key operators are:
+
, -
, *
, **
, /
, //
, %
)and
, or
, not
)==
, !=
, >
, >=
, <
, <=
)=
, +=
, -=
, *=
, /=
)in
)1 + 1
2
5 - 3
2
6 / 2
3.0
4 * 4
16
# Exponentiation <- Python comments start with #
2 ** 4
16
3 != 1 # Not equal
True
3 > 3 # Greater than
False
3 >= 3 # Greater than or equal
True
False or True # True if either first or second operand is True, False otherwise
True
3 > 3 or 3 >= 3 # Combining 3 Boolean expressions
True
x = 3
x
3
x += 2 # Increment assignment, equivalent to x = x + 2
x
5
As =
(assignment) and ==
(equality comparison) operators appear very similar, they sometime can create confusion.
x = 3
x
3
x == 3
True
Operator in
returns True
if an object of the left side is in a sequence on the right.
'a' in 'abc'
True
4 in [1, 2, 3] # [1,2,3] is a list
False
4 not in [1, 2, 3]
True
Python objects can have scalar and non-scalar types. Scalar objects are indivisible.
4 main types of scalar objects in Python:
int
)float
)bool
)None
)type(7)
int
type(3.14)
float
type(True)
bool
type(None)
NoneType
int(3.14) # Scalar type conversion (casting)
3
In contrast to scalars, non-scalar objects, sequences, have some internal structure. This allows indexing, slicing and other interesting operations.
Most common sequences in Python are:
str
) - immutable ordered sequence of characterstuple
) - immutable ordered sequence of elementslist
) - mutable ordered sequence of elementsset
) - mutable unordered collection of unique elementsdict
) - mutable unordered collection of key-value pairss = 'time flies like a banana'
t = (0, 'one', 1, 2)
l = [0, 'one', 1, 2]
o = {'apple', 'banana', 'watermelon'}
d = {'apple': 150.0, 'banana': 120.0, 'watermelon': 3000.0}
type(s)
str
type(t)
tuple
type(l)
list
type(o)
set
type(d)
dict
[]
to supply the index (indices) of elements:object[index]
Source: xkcd
Extra: Why Python uses 0-based indexing by Guido van Rossum
Extra: Why numbering should start at zero by Edsger Dijkstra
s
'time flies like a banana'
len(s) # length of string (including whitespaces)
24
s[0] # Subset 1st element (indexing in Python starts from zero!)
't'
s[5:] # Subset all elements starting from 6th
'flies like a banana'
s + '!' # Strings can be concatenated together
'time flies like a banana!'
object.method()
as opposed to function(object)
len(s) # Function
24
s.upper() # Method (makes string upper-case)
'TIME FLIES LIKE A BANANA'
s.capitalize() # Note that only the first character gets capitalized
'Time flies like a banana'
s.split(sep = ' ') # Here we supply an argument 'sep' to our methods call
['time', 'flies', 'like', 'a', 'banana']
s.replace(' ', '-') # Arguments can also be matched by position, not just name
'time-flies-like-a-banana'
'-'.join(s.split(sep = ' ')) # Methods calls can be nested within each other
'time-flies-like-a-banana'
t # Tuples can contain elements of different types
(0, 'one', 1, 2)
len(t)
4
t[1:]
('one', 1, 2)
t + ('three', 5) # Like strings tuples can be concatenated
(0, 'one', 1, 2, 'three', 5)
l # Like tuples lists can contain elements of different types
[0, 'one', 1, 2]
l[1] = 1 # Unlike tuples lists are mutable
l
[0, 1, 1, 2]
t[1] = 1 # Compare to tuple
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-52-4e4114da061e> in <module> ----> 1 t[1] = 1 # Compare to tuple TypeError: 'tuple' object does not support item assignment
l
[0, 1, 1, 2]
l[1:] # Subset all elements starting from 2nd
[1, 1, 2]
l[-1] # Subset the last element
2
l[::2] # Subset every second element, list[start:stop:step]
[0, 1]
l[::-1] # Subset all elements in reverse order
[2, 1, 1, 0]
o
{'apple', 'banana', 'watermelon'}
{'apple', 'apple', 'banana', 'watermelon'} # Sets retain only unique values
{'apple', 'banana', 'watermelon'}
{'apple'} < o # Sets can be compared (e.g. one being subset of another)
True
o[1] # Unlike strings, tuples and lists, sets are unordered
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-61-6a3d97725b65> in <module> ----> 1 o[1] # Unlike strings, tuples and lists, sets are unordered TypeError: 'set' object is not subscriptable