Python
is a general purpose, high level language.- It is dynamically typed and interpretered language.
- Python runs mostly on all modern operating systems.
- Windows - http://docs.python-guide.org/en/latest/starting/install/win/
- GNU/Linux - http://docs.python-guide.org/en/latest/starting/install/linux/
- Mac OSX - http://docs.python-guide.org/en/latest/starting/install/osx/
- Type
python
in theCommand Prompt
orTerminal
. The output should look like
➜ learnpythoninminutes python
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
Command
takes you toPython Interactive Shell
. The important thing to note here isPython 2.7.5
which sayspython version
installed in the machine. All the tutorial will focus onPython 2.7.x
.
>>> print("Welcome to learn python in minutes tutorial")
Welcome to learn python in minutes tutorial
>>> place = "Bangalore"
>>> duration = 180 # Duration in minutes. This is a comment!
>>> author = "Kracekumar"
>>> print("Welcome to learn python in minutes tutorial by %s for %d minutes in
%s" % (author, duration, place))
Welcome to learn python in minutes tutorial by Kracekumar for 180 minutes in
Bangalore
>>>
indicates we are inside Python interpreter.- Interpreter reads everyline, evaluates and returns result if any.
place = "Bangalore"
is variable. Left hand side of=
is the name of the variable and right hand side is the value.- No need to give what is the type of the variable.
print()
is function which prints result tostandard output
, here it is Python Interpreter.duration = 180
is a variable which storesint
value.%s, %d
are format specifiers likeC
.
Python
has very good support for number crunching.
>>> duration_in_mins = 180
>>> duration_in_mins / 60 # Hours, in int
3
>>> duration_in_mins / 60.0 # Hours, in float
3.0
>>> duration_in_mins * 60 # In seconds
10800
>>> 12 + 23 # Simple add
35
>>> 12 - 23 # Subtraction
-11
>>> 12 / 23 # Division
0
>>> 12 / 23.0 # Note the denominator
0.5217391304347826
>>> 12 * 23.0 # multiply
276.0
>>> 3 % 2 # Modulo
1
>>> 12 ** 23.0 # 12 power of 23
6.624737266949237e+24 # When number is too large scientific notation is used
>>> 12 ** 12
8916100448256
>>> 12 ** 18
26623333280885243904L # `L` at the end says it is a long number.
>>> 12 + 20 * 2 - 4 * 2 / 2.0
48.0
>>> 12 + (20 * 2) - 4 * (2 / 2.0)
48.0
>>> 12 + (20 * 2) - (4 * 2 ) / 2.0
48.0
- While dividing two numbers if both are
int
result will beint
elsefloat
.
Let's see how expression are handled without brackets.
12 + 20 * 2 - 4 * 2 / 2.0
12 + 40 - 4 * 2 / 2.0
12 + 40 - 8 / 2.0
12 + 40 - 4.0
52 - 4.0
48.0
- Expression is evaluated from
Left -> Right
.BODMAS (Bracket Of Division Multiplication)
rule is followed while evaluating expression.
- It is possible to create multiple variables in same line.
>>> a, b = 12, 23 # Multiple declartion
>>> print(a, b)
(12, 23)
>>> b, a = a, b
>>> print a, b # print is a statement
23 12
- Woot! We swapped two numbers without intermediate variable.
a = 23
creates a new variable, no need to mention valuetype
.- No need to use
bracket
while evaluating expression unless explict perference is needed. - Python automatically rounds off number during division if both the numbers are
int
.
single quote ('python') or double quote ("python") or triple single/double quotes
can be used to create a new string.strings
are immutable data type.
author = 'Kracekumar'
one_liner_about_python = "Python is simple and powerful language"
description = """Python is a general purpose, high level language.
It is dynamically typed and interpretered language.
"""
print(author)
print(one_liner_about_python)
print(description)
complete_msg = """Author: {}
One liner about Python:
- {}
Long Description:
{}""".format(author, one_liner_about_python, description)
print(complete_msg)
Kracekumar
Python is simple and powerful language
Python is a general purpose, high level language.
It is dynamically typed and interpretered language.
Author: Kracekumar
One liner about Python:
- Python is simple and powerful language
Long Description:
Python is a general purpose, high level language.
It is dynamically typed and interpretered language.
- Everything is an object in Python.
string
has lot of methods likeupper
,lower
,strip
etc ..
print("lower".upper())
print("upper".lower())
print("captialize".capitalize())
print(" extra spaces ".strip()) # Very useful in web development while cleaning user input
print("find a word's position in the sentence".find('word')) # returns starting position
print("how many times the letter `e` is present in the sentence".count('e'))
print("Replace delete with remove".replace('delete', 'remove'))
print("Python is simple and powerful language".startswith('Python'))
LOWER
upper
Captialize
extra spaces
7
11
Replace remove with remove
True
language = 'python'
print(language[0]) # Print first character
print(language[-1]) # print last character
print(len(language)) # builtin function, Find the length of the string
print(language[0:2]) # Print first 3 characters. Slicing `0` is starting index and `2` is last index.
print(language[-3:]) # print last three characters
language = language + "." # # Add a dot after python. Here new variable is created
print(language)
p
n
6
py
hon
python.
string
is immutable datatype.string
has lot of useful methods for data processing.negative index
can be used for accessing the string content from reverse direction.slicing
is used for getting partial content from the string.
True
andFalse
are Boolean values in Python.None
is used to represent absence of a value.Python
usesif
,elif
,else
for branching.==
is used to check two values are equal,!=
is used for non equality checks.
print(23 == 32)
print(23 != 32)
print(True == False)
print(True != False)
False
True
False
True
Write a program if a given number is divisible by 3
print fizz
, 5
print
buzz
, divisible by both 3 and 5
print fizz buzz
else print nothing
.
Create a new file called fizzbuzz.py
and write the code. python fizzbuzz.py
should execute the code.
# fizzbuzz.py
number = 23
print(number)
if number % 15 == 0:
print("fizz buzz")
elif number % 3 == 0:
print("fizz")
elif number % 5 == 0:
print("buzz")
else:
print("nothing")
examples $ python fizzbuzz.py
23
nothing
Python
uses indentation to separate block. So use4 spaces
ortabs which converts to 4 spaces
. Don't mix both.:
at the end ofif, elif, else
statement.
Python
uses keywordand, or, not
forand, or, not
operations.
print(True and False)
print(23 and 12) # Watch for output
print(True or False)
print(23 or 12) # Watch for output
print("python" or "javascript")
print("python" and "javascript")
print(not 23)
False
12
True
23
python
javascript
False
True, False
areBoolean
values.None
represents absence of value.- Logical operators are
and, or, not
. Logic operators can be used with any data type. ==, !=
are comparision operators.
List
is collection of heterogenous data type.List
is similar to array in other languages.- Size of the list grows over the course of the program.
collection = ['Ruby', 23, 45.9, True] # Collection of different elements.
"""Representaion of list
---------------------------
|'Ruby'| 23 | 45.9 | True|
---------------------------
0 1 2 3
"""
print(collection)
# Access the first element
print(collection[0])
# Access the last element
print(collection[-1])
# Replace the first element
collection[0] = 'Python'
print(collection[0])
# Add an element at the last position
collection.append("last")
print(collection[-1])
# Insert an element at position 2
print(collection)
collection.insert(2, 12)
print(collection)
# Delete the last element
del collection[-1]
print(collection)
# Length of the list
print(len(collection))
['Ruby', 23, 45.9, True]
Python
True
Python
last
['Python', 23, 45.9, True, 'last']
['Python', 23, 12, 45.9, True, 'last']
['Python', 23, 12, 45.9, True]
5
List
can have list inside it.
nested_collection = [['apple', 'orange'], ['Python', 'Go']]
print(nested_collection) # Access first element in first list
print(nested_collection[0][0])
[['apple', 'orange'], ['Python', 'Go']]
apple
collection = ['Python', 23, 45.9, True]
print(collection.count(23))
print(collection.index(23)) # If not found Exception will be raised.
print('23' in collection) # Check if an element is present in list
print('p' in 'python') # `in` works on strings, list etc..
1
1
False
True
List
is collection of hetergenous data types.List
can have nested elements.append
adds the element at the end of the list.in
operator is used to check presence of an element.
for
loop can be used against data structure which is iterable likelist, string
.
for i in ['Python', 23, 45.9, True]: # During every iteration i value is replaced, `python` -> `23` -> `45.9` -> `True`
print(i)
Python
23
45.9
True
for ch in "Python":
print(ch)
P
y
t
h
o
n
for number in range(0, 10): # Produces list of numbers starting from 0 til 9, 10 is excluded.
if number % 2 == 0:
print("Even")
else:
print("Odd")
Even
Odd
Even
Odd
Even
Odd
Even
Odd
Even
Odd
- During every iteration temporary variable holds the value in the iterable.
:
at the end of thefor
statement is important.- Similar to
if
statement body offor
loop is indented.
Function
is unit which may take arguments, compute and returns a value. Sometimesfunction
doesn't return a value.
def square(x): # No need to specify type of the argument.
return x * x
def cube(x):
return square(x) * x
def msg(): # Function with no arguments and doesn't return any value
print("End")
print(square(2))
print(square(23))
msg()
4
529
End
def square(x=2): # if x didn't receive any value, 2 is taken.
return x * x
print(square(23))
print(square())
529
4
Function
can take function as an argument.
def fxy(f, x, y): # f(x, y) = f(x) . f(y)
return f(x) * f(y)
def square(x):
return x * x
print(fxy(square, 2, 3))
36
Function
is small unit of computation which may take arguments and may return values.Function
can be passed to a function as an argument.Function
body should be indented likeif
statement.
Python
has lot of builtin functions.
print(sum([1, 2, 3, 4])) # 10
print(max([1, 2, 3, 4])) # 4
print(min([1, 2, 3, 4])) # 1
print(sorted([1, 2, 3, 4])) # Ascending order
print(sorted([1, 2, 3, 4], reverse=True)) # Descending order
print(float(23)) # Typecast into float
print(list("23")) # String -> list
print(str(23))
print(int('23'))
# Find data type
print(type(23))
print(type([2]))
print(type('23'))
10
4
1
[1, 2, 3, 4]
[4, 3, 2, 1]
23.0
['2', '3']
23
23
<type 'int'>
<type 'list'>
<type 'str'>
- There are around 80 builtin functions, complete details is avaiable here https://docs.python.org/2/library/functions.html.
class
is a template for creating objects.Objects
containsattributes
andmethods
.Object
is created by invoking theconstructor
orinitializer
.Attributes
andmethods
may belong toinstance
orclass
.
Create a class Person
with attributes first_name
, last_name
, age
. Add
full_name
and is_major
as methods to class Person
.
class Person:
def __init__(self, first_name, last_name='', age=18): # self is always first argument in all instance method
# __init__ is initializer
self.first_name = first_name
# `self` is used for accessing instance attribute and method.
self.last_name = last_name
self.__age = age # Private like attribute
def full_name(self):
# Instance method
return self.first_name + ' ' + self.last_name
def get_age(self):
# Since __age is private like variable we need to have getters and setters. Getter
return self.__age
def set_age(self, age):
# Setter
self.__age = age
def is_major(self):
return self.__age >= 18
guido = Person("Guido", "van rossum", 58) # __init__ of Person is called
krace = Person("Kracekumar", "Ramaraju", 24)
# Access instance first_name, last_name
print(guido.first_name)
print(guido.last_name)
print(krace.first_name)
print(krace.last_name)
# Access instance methods
print(guido.full_name()) # self is passed implicitly in the background.
print(krace.is_major())
# Modif the age, first_name
krace.set_age(12)
krace.first_name = 'kracekumar'
print(krace.get_age(), krace.first_name)
print(krace.is_major())
Guido
van rossum
Kracekumar
Ramaraju
Guido van rossum
True
(12, 'kracekumar')
False
__init__
is initializer in Python.self
is passed as first argument in method.- Attributes starting
__
are unaccessible with.
notation .
Dictionary
isHash Map or Associative Array
in other programming languages.- Every entry in dictionary consist of
Key, Value
pair.
months = {'jan': 31, 'feb': 28, 'mar': 31, 'apr': 30} # Colon is used to separate key and value
# `jan` is key and `31` is value
""" Visual representation of Dictionary
-----------
|Key|Value|
-----------
|jan|31 |
-----------
|feb|28 |
-----------
|mar|31 |
-----------
|apr|30 |
-----------
"""
print(months) # Dictionary don't maintain the order of insertion.
print(months['jan']) # Values in dictionary are accessed using key, in list index is used.
print(months.get('jan')) # .get returns None if the key is missing
print('dec' in months) # `in` is used to check presence of key in dictionary.
print(len(months)) # len function is used to find total key, value pair in dictionary.
for key, value in months.items(): # .items() returns two values during every iteration. First is key, second is value
print(key, '->', value)
months['feb'] = 29 # Leap year! if key is already present value will be replaced else key, value pair will be added.
print(months)
months['dec'] = 31
print(months)
{'jan': 31, 'apr': 30, 'mar': 31, 'feb': 28}
31
31
False
4
('jan', '->', 31)
('apr', '->', 30)
('mar', '->', 31)
('feb', '->', 28)
{'jan': 31, 'apr': 30, 'mar': 31, 'feb': 29}
{'jan': 31, 'apr': 30, 'dec': 31, 'mar': 31, 'feb': 29}
Dictionary
is used when representation is key, value pair likemonthly sales, student marks stored subject wise
.Dictionary
lookup takes constant time.
Dictionary
doesn't maintain the key, value pair order..get()
method is used to value of the key in dictionary. Ifkey
is missingNone
is returned.
- When something goes unexpected interpreter raises
Exception
like dividing by zero, accessing the missing array index. Exceptions
can be caught and acted accordingly.
l = [1, 2, 3]
print(l[5]) # This raises IndexError since list only contains 3 elements.
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-56-5e770730b19a> in <module>()
1 l = [1, 2, 3]
----> 2 print(l[5]) # This raises IndexError since list only contains 3 elements.
IndexError: list index out of range
d = {'a': 1}
print(d['b']) # Raises KeyError
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-57-945bd7e85bd3> in <module>()
1 d = {'a': 1}
----> 2 print(d['b']) # Raises KeyError
KeyError: 'b'
try:
l = [1, 2, 3]
print(l[5])
except IndexError as e:
print(e)
list index out of range
try:
d = {'a': 1}
print(d['b'])
except KeyError as e:
print(e)
'b'
try:
l = [1, 3, 3]
d = {'a': 1}
print(l[5], d['a'])
except (IndexError, KeyError) as e:
print(e)
finally:
print("end")
list index out of range
end
try, except, finally
are three exception handling blocks.except
can catch more than oneException
type.
- Learn Python HardWay - http://learnpythonthehardway.org/
- Build your search engine - https://www.udacity.com/course/cs101
- Official Docs: https://docs.python.org/2/
- Email: me@kracekumar.com
- Twitter: https://twitter.com/kracetheking
- Thanks Praseetha, Mudassir Ali for feedback.