BasÃ© sur Learning Python in Y minutes

``````# Single line comments start with a number symbol.

""" Multiline strings can be written
using three "s, and are often used
"""

####################################################
# 1. Primitive Datatypes and Operators
####################################################

# You have numbers
3  # => 3

# Math is what you would expect
1 + 1  # => 2
8 - 1  # => 7
10 * 2  # => 20
35 / 5  # => 7
5 / 2  # => 2 /!\ in Python 2, divisions on ints apply floor directly, you need to use floats. This is not true in Python 3
7 % 3  # => 1 (modulo)
2 ** 4  # => 16 = 2^4 (exponentiation)

# To fix division we need to learn about floats.
2.0  # This is a float
11.0 / 4.0  # => 2.75
5.0 // 3.0  # => 1.0 # forced integer division

# Booleans and operations
True and False  # => False
False or True  # => True
not True  # => False
not False  # => True

# Comparisons
1 == 1  # => True
2 == 1  # => False
1 != 1  # => False
2 != 1  # => True
1 < 10  # => True
1 > 10  # => False
2 <= 2  # => True
2 >= 2  # => True

# Strings
"This is a string."
'This is also a string.'
"Hello " + "world!"  # => "Hello world!"
"This is a string"[0]  # => 'T'
len("This is a string")  # => 16
"%d %s cost %f %s" % (3, 'apples', 1.5, 'euros') # String formatting with %, youc usually use variables in the ()

# None is an object
None  # => None
"etc" is None  # => False (compare None with is)
None is None  # => True

# Cast
float(3) # => 3.0
int(3.5)  # => 3

####################################################
# 2. Variables and Collections
####################################################

# No need to declare variables before assigning to them.
some_var = 5  # Convention is to use lower_case_with_underscores
some_var  # => 5

# Declare list
li = [] # empty
other_li = [4, 5, 6] # prefilled

# Add stuff to the end of a list with append
li.append(1)  # li is now [1]
li.append(2)  # li is now [1, 2]
li.append(4)  # li is now [1, 2, 4]
li.append(3)  # li is now [1, 2, 4, 3]
li.pop()  # => 3 and li is now [1, 2, 4]  (Remove from the end with pop)

# Indexing
li[0]  # => 1 (indexing list)
li[0] = 42 # (change item with index)
li[-1]  # => 3 (last element)
li[1:3]  # => [2, 4] (items 1 to 2 <index of first element>:<index of last element + 1>)
li[2:]  # => [4, 3] (items 2 to end of list)
li[:3]  # => [1, 2, 4] (items 0 to 2)
len(li)  # => 6 (length of the list)

# Tuples are like lists but are immutable
tup = (1, 2, 3)
tup[0]  # => 1
len(tup)  # => 3
# You can unpack tuples (or lists) into variables
a, b, c = (1, 2, 3)  # a is now 1, b is now 2 and c is now 3

# Dictionaries store mappings
empty_dict = {} # empty
filled_dict = {"one": 1, "two": 2, "three": 3} # prefield
filled_dict["one"]  # => 1
filled_dict.keys()  # => ["three", "two", "one"]
filled_dict.values()  # => [3, 2, 1]
filled_dict.items()  # => [("one", 1), ("two", 2), ("three", 3)]
filled_dict["four"] = 4  # now, filled_dict["four"] => 4

####################################################
#  3. Control Flow
####################################################

# Python has a print statement
print("I'm Python. Nice to meet you!")  # => I'm Python. Nice to meet you!

# Let's just make a variable
some_var = 5

# Here is an if statement. Indentation is significant in python!
# prints "some_var is smaller than 10"
if some_var > 10:
print("some_var is totally bigger than 10.")
elif some_var < 10:  # This elif clause is optional.
print("some_var is smaller than 10.")
else:  # This is optional too.
print("some_var is indeed 10.")

"""
For loops iterate over lists
prints:
dog is a mammal
cat is a mammal
mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
# You can use {0} to interpolate formatted strings. (See above.)
print("{0} is a mammal".format(animal))

"""
"range(number)" returns a list of numbers
from zero to the given number
prints:
0
1
2
3
"""
for i in range(4):
print(i)

"""
"range(lower, upper)" returns a list of numbers
from the lower number to the upper number
prints:
4
5
6
7
"""
for i in range(4, 8):
print(i)

"""
While loops go until a condition is no longer met.
prints:
0
1
2
3
"""
x = 0
while x < 4:
print(x)
x += 1  # Shorthand for x = x + 1

####################################################
# 4. Functions
####################################################

# Use "def" to create new functions
print("x is {0} and y is {1}".format(x, y))
return x + y  # Return values with a return statement

# Calling functions with parameters
add(5, 6)  # => prints out "x is 5 and y is 6" and returns 11
add(y=6, x=5)  # Another way to call functions is with keyword arguments

# Optional parameters and default values
def myfunc(x, y, z=3, name="Test"):
print("%s: %d" % (name, x+y+z))
return (x+y, y+z) # returning a tuple

xy, yz = myfunc(1, 2) # => Test: prints 6, return (3, 5) unpacked in xy and yz variables
myfunc(1, 2, name="Other") # => Other: 6
myfunc(1, 2, 0, "Other") # => Other: 3 (using position only)
myfunc(1, 2, 0, name="Other") # => Other: 3 (without giving 3rd arg "z")
myfunc(1, 2, name="Other", z=0) # => Other: 3 (keyword args don't have specific order)

####################################################
# 5. Modules
####################################################

# You can import modules
import math

print math.sqrt(16)  # => 4

# You can get specific functions from a module
from math import ceil, floor

print ceil(3.7)  # => 4.0
print floor(3.7)  # => 3.0

# You can import all functions from a module.
# Warning: this is not recommended
from math import *
``````