According to Wikipedia:
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.
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 is also unique from Java in that there is a strong sense of community among Python programmers. One consequence (or virtue, depending on your point of view) of this is that while there are often several ways of accomplishing something in Python, there is quite often one Pythonic way of doing it. Make sure you pay attention to how things are shown in this overview!
Python includes four different types of number literals:
1
, -3
2.0
, 4e-54
5 + 4j
, -3-8j
True
, False
And with these have several standard operators:
+
- addition-
- subtraction*
- multiplication/
- division (5 / 2 = 2.5
)//
- division with integer truncation (5 // 2 = 2
)%
- modulus**
- exponentiationInstead of a statically-allocated block of memory for an array, as in Java, Python provides the list
type as a dynamic alternative. Not only are these lists dynamically sized (i.e., resizable), they can store a mixture of types:
[]
[1, 2, 3]
[1, "two", 3.0]
Lists in Python have a very powerful indexing ability. We can index from the front using 0-indexing, just like Java:
>>> x = ["one", "two", "three"]
>>> print(x[0])
one
>>> print(x[2])
three
However, we can also index going backwards with negative indices, starting with -1:
>>> x = ["one", "two", "three"]
>>> print(x[-1])
three
>>> print(x[-3])
one
We can also get a sub-list using Python's m:n
'slice' syntax, where m
is the starting index and n
is the final index, exclusive (not included). For convenience, we can also use :n
to start from the beginning and m:
to go to the end:
>>> x = ["one", "two", "three", "four"]
>>> print(x[1:-1])
['two', 'three']
>>> print(x[0:3])
['one', 'two', 'three']
>>> print(x[:2])
['one', 'two']
>>> print(x[-3:])
['two', 'three', 'four']
These various indexing abilities allow us to change the contents of a list very easily, even changing the size:
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x[4] = 5.0
>>> x[8:9] = []
>>> print(x)
[1, 2, 3, 4, 5.0, 6, 7, 8]
>>> x[5:7] = ["six", "six and a half", "seven"]
>>> print(x)
[1, 2, 3, 4, 5.0, 'six', 'six and a half', 'seven', 8]
Python includes several functions and operators that work on lists:
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> len(x)
9
>>> min(x)
1
>>> max(x)
9
>>> 2 in x
True
>>> 4.5 in x
False
>>> del x[4:6]
>>> x
[1, 2, 3, 4, 7, 8, 9]
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x + [10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [-1, 0] + x
[-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x * 2
[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Python's standard library reference (available online) will include all methods included in the list
class, vastly extending the power of lists.
A tuple (two-pull) is an immutable list, useful in returning multiple values from functions and acting as keys for dictionaries. Tuples are created using parentheses instead of square brackets:
()
(1,) # One-element tuples still need a comma!
(1, "two", 3.0)
Since tuples are immutable, we can't use indexing to add, remove, or replace any items in the tuple, but we can still extract items and sub-tuples:
>>> x = (1, 2, 3, 4)
>>> print(x[1])
2
>>> print(x[2:])
(3, 4)
Most of the same builtin functions and operators (in
, +
, *
, len()
, max()
, min()
) all work the same on tuples as they do lists. We can also convert easily between tuples and lists:
>>> x = [1, 2, 3, 4]
>>> tuple(x)
(1, 2, 3, 4)
>>> x = (1, 2, 3, 4)
>>> list(x)
[1, 2, 3, 4]
Strings are represented in three ways in Python:
"A string in double quotes can contain 'single quote' characters."
'A string in single quotes can contain "double quote" characters.'
'''\tThis string starts with a tab and ends with a newline character.\n'''
"""This is a triple double quoted string, the only kind that can
contain real newlines."""
The same functions and operators that work on lists and tuples also work on strings. Additionally, we can use index and slice notation as well to extract sub-strings.
Dictionaries are Python's equivalent of Java's Map
, being an implementation of an associative array. Instead of storing values with simple integer indices, we can instead index values using any class that is immutable (numbers, strings, tuples).
We can pass the len()
function a dictionary to find the number of key-value pairs, the del
statement to slice key-value pairs, and several other useful methods:
>>> x = {1: "one", 2.0: "two", "three": 3}
>>> x["third"] = 3
>>> x.get(1)
'one'
>>> x.get(4, "Key not in list")
'Key not in list'
>>> x.keys()
dict_keys([1, 2.0, 'three', 'third'])
>>> list(x.keys())
[1, 2.0, 'three', 'third']
>>> list(x.values())
['one', 'two', 3, 3]
>>> 1 in x
True
>>> "one" in x # We can get keys, not values with 'in'
False
Sets are lists with solely unique members. In fact, in Python, sets work in an identical fashion to lists:
>>> x = set([1, 2, 3, 1, 4, 5.0])
>>> x
{1, 2, 3, 4, 5.0}
>>> 2 in x
True
>>> "python" in x
False
In Java and C, blocks of code were delimited with curly braces {}
, like so:
int main(int argc, char** argv)
{
return 0;
}
public static void main(String[] args)
{
return;
}
Due to this, indentation was not a significant factor, as shown in these equivalent code snippets:
int main(int argc, char** argv) {
return 0;
}
public static void main(String[] args){return;}
It was up to the programmer to decide on a consistent style to follow, often modeled upon community guidelines. Python, however, follows a different philosophy. Blocks of code start with a colon and are delimited with indentation, with a community standard of 4 spaces (NOT tabs!), allowing Python code to be remarkably consistent across different programmers:
if __name__ == "__main__":
print("Hello, Python!")
Both if
-statements and while
-loops in Python behave every similarly to their counterparts in Java. There are a few things to note, however:
x = 4
if x < 4: # No parentheses around the predicate (Boolean expression)
y = -1
z = 5
elif x > 5: # 'elif' instead of 'else if'
y = 1
z = 11
else: # Colon+indentation denoting a block of code
y = 0
z = 10
print(x, y, z)
x = 0
while x < 10: # No parentheses around the predicate, and Python blocks
print(x, end=" ")
x += 1
Python's for
-loop acts not like Java's normal for
-loop, but instead like Java's foreach loop for the Collection API, modeled below:
// Assuming variable list is a LinkedList of Strings
for (String str : list) {
System.out.println(str);
}
For
-loops in Python are most often used for iterating over the builtin collections, so they are constructed for that purpose:
# Assuming str_list is a list of strs
for str in str_list:
print(str)
We can, however, model a traditional for
-loop with the range()
function:
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
for i in range(0, 10):
print(i)
range()
takes at least two arguments, the inclusive start (i = 0
), and the exclusive end (i < 10
), and optionally a third argument giving the 'step', or the amount to increment by (by default i += 1
, needs to be negative to iterate backwards):
>>> for i in range(10, 0, -1):
print(i, end=" ")
10 9 8 7 6 5 4 3 2 1
The biggest differences between Python and Java functions are how we deal with arguments. We can use positional arguments, like Java (passed to the function in the order they were defined in), however we can also use keyword arguments to 'name' our parameters:
>>> def func1(x, y, z):
print(x, y, z)
>>> a = 3
>>> func1(a, 4, 5)
3 4 5
>>> func1(a, z=5, y=4)
3 4 5
>>> def func2(x, y=100, z=42):
print(x, y, z)
>>> func2(a)
3 100 42
In order to deal with the issue of variadic functions (functions that take a variable number of arguments, like print()
), we have a way to gather excess positional arguments in a tuple, and excess keyword arguments in a dictionary:
>>> def func3(x, y=5, z=5, *tup):
print((x, y, z) + tup)
>>> func3(5, 5, 5, 1, 2, 3, 4)
(5, 5, 5, 1, 2, 3, 4)
>>> def func4(x, y=5, z=5, **dict):
print(x, y, z, dict)
>>> func4(a, m=42, n=100)
3 5 5 {'m': 42, 'n': 100}
>>>