Learn Python in Y Minutes
Learn Python in Y Minutes
%2F%2Flearnxinyminutes.com%2Fdocs%2Fpython%2F&text=Learn+X+in+Y+minutes%2C+where+X%3Dpython)
Python was created by Guido Van Rossum in the early 90s. It is now one of the most popular
languages in existence. I fell in love with Python for its syntactic clarity. It’s basically executable
pseudocode.
Note: This article applies to Python 2.7 speci cally, but should be applicable to Python 2.x. Python
2.7 is reaching end of life and will stop being maintained in 2020, it is though recommended to
start learning Python with Python 3. For Python 3.x, take a look at the Python 3 tutorial
(http://learnxinyminutes.com/docs/python3/).
It is also possible to write Python code which is compatible with Python 2.7 and 3.x at the same
time, using Python __future__ imports (https://docs.python.org/2/library/__future__.html).
__future__ imports allow you to write Python 3 code that will run on Python 2, so check out the
Python 3 tutorial.
# Single line comments start with a number symbol.
####################################################
# 1. Primitive Datatypes and Operators
####################################################
# Result of integer division truncated down both for positive and negative.
5 // 3 # => 1
5.0 // 3.0 # => 1.0 # works on floats too
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
# Modulo operation
7 % 3 # => 1
# Boolean Operators
# Note "and" and "or" are case-sensitive
True and False # => False
False or True # => True
# Equality is ==
1 == 1 # => True
2 == 1 # => False
# Inequality is !=
1 != 1 # => False
2 != 1 # => True
# More comparisons
1 < 10 # => True
1 > 10 # => False
2 <= 2 # => True
2 >= 2 # => True
# ... or multiplied
"Hello" * 3 # => "HelloHelloHello"
# None is an object
None # => None
####################################################
# 2. Variables and Collections
####################################################
# "setdefault()" inserts into a dictionary only if the given key isn't present
filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5
filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5
# Sets store ... well sets (which are like lists but can contain no duplicates)
empty_set = set()
# Initialize a "set()" with a bunch of values
some_set = set([1, 2, 2, 3, 4]) # some_set is now set([1, 2, 3, 4])
####################################################
# 3. Control Flow
####################################################
"""
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
####################################################
"""
all_the_args(1, 2, a=3, b=4) prints:
(1, 2)
{"a": 3, "b": 4}
"""
# you can pass args and kwargs along to other functions that take args/kwargs
# by expanding them with * and ** respectively
def pass_all_the_args(*args, **kwargs):
all_the_args(*args, **kwargs)
print varargs(*args)
print keyword_args(**kwargs)
# Function Scope
x = 5
def set_x(num):
# Local var x not the same as global variable x
x = num # => 43
print x # => 43
def set_global_x(num):
global x
print x # => 5
x = num # global var x is now set to 6
print x # => 6
set_x(43)
set_global_x(6)
return adder
add_10 = create_adder(10)
add_10(3) # => 13
####################################################
# 5. Classes
####################################################
# Initialize property
self.age = 0
# Instantiate a class
i = Human(name="Ian")
print i.say("hi") # prints out "Ian: hi"
j = Human("Joel")
print j.say("hello") # prints out "Joel: hello"
####################################################
# 6. Modules
####################################################
dir(math)
####################################################
# 7. Advanced
####################################################
# Generators
# A generator "generates" values as they are requested instead of storing
# everything up front
# The following method (*NOT* a generator) will double all values and store it
# in `double_arr`. For large size of iterables, that might get huge!
def double_numbers(iterable):
double_arr = []
for i in iterable:
double_arr.append(i + i)
return double_arr
# Running the following would mean we'll double all values first and return all
# of them back to be checked by our condition
for value in double_numbers(range(1000000)): # `test_non_generator`
print value
if value > 5:
break
# We could instead use a generator to "generate" the doubled value as the item
# is being requested
def double_numbers_generator(iterable):
for i in iterable:
yield i + i
# Running the same code as before, but with a generator, now allows us to iterate
# over the values and doubling them one by one as they are being consumed by
# our logic. Hence as soon as we see a value > 5, we break out of the
# loop and don't need to double most of the values sent in (MUCH FASTER!)
for value in double_numbers_generator(xrange(1000000)): # `test_generator`
print value
if value > 5:
break
# BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in
`test_generator`?
# Just as `double_numbers_generator` is the generator version of `double_numbers`
# We have `xrange` as the generator version of `range`
# `range` would return back and array with 1000000 values for us to use
# `xrange` would generate 1000000 values for us as we request / iterate over those
items
# Just as you can create a list comprehension, you can create generator
# comprehensions as well.
values = (-x for x in [1, 2, 3, 4, 5])
for x in values:
print(x) # prints -1 -2 -3 -4 -5 to console/terminal
# Decorators
# A decorator is a higher order function, which accepts and returns a function.
# Simple usage example – add_apples decorator will add 'Apple' element into
# fruits list returned by get_fruits target function.
def add_apples(func):
def get_fruits():
fruits = func()
fruits.append('Apple')
return fruits
return get_fruits
@add_apples
def get_fruits():
return ['Banana', 'Mango', 'Orange']
return wrapper
@beg
def say(say_please=False):
msg = "Can you buy me a beer?"
return msg, say_please
Free Online
Dead Tree
Programming Python
(http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?
ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits0
20)
Dive Into Python (http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?
ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits0
20)
Python Essential Reference (http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?
ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits0
20)