Here’s a precise manual I put together for convenient learning of Python programming language for a beginner and as an easy reference. Bookmark or re-download periodically as I will keep updating this page for improvement. Installation and some other instructions are currently only for Mac OS X operating system.
\[\\[0.2in]\]
http://www.diveintopython3.net/porting-code-to-python-3-with-2to3.html
\[\\[0.4in]\]
brew install python3 # for latest version of python 3
# or go to python.org, download the latest version installation file, and click install
# (In Windows, make sure to check the box 'add python to path' in the installation window.)
PyCharm is the best python IDE. IPython is probably the best command line REPL application you can find (provides some nice features like syntax highlighting, code completion, and much more). Install it using commandline and open as follows:
pip install ipython
ipython
\[\\[0.4in]\]
sudo easy_install pip
python3 -m pip install # install for python3 version of python
python3 -m pip install --upgrade pip # upgrade pip
pip install <package> #install a package
pip install <package>==<version>
python -m pip install <package>
pip install –U <package> #upgrade a package
pip uninstall <package> #uninstall a package
pip show <package> #show package details
\[\\[0.4in]\]
Open Terminal (in Mac). Type python3
to open Python REPL
(Read-Evaluate-Print-Loop). Type quit()
to close REPL. The
same interactive prompt can be accessed by using the IDLE application
that’s installed by Python automatically (in Applications/Python
directory in Mac).
## Nilotpal
\[\\[0.4in]\]
To run, a python program from file, save the script into prog.py and then run in commandline using
python3 prog.py
For shell script, write prog.py as
#!/usr/bin/python3
name = "Nilotpal"
print(name)
Then, in the terminal
chmod u+x program.py. #set execution permission
./program.py
\[\\[0.4in]\]
Indentation in Python is meaningful. You cannot indent randomly like this (will give error):
name = "Flavio"
print(name)
\[\\[0.4in]\]
## 'This is called docstring'
\[\\[0.4in]\]
import sys
sys.version # shows Python version, platform, etc.
import datetime
datetime.datetime.now() # shows current date and time
import os
os.getcwd() # shows the current working directory
os.chdir("/Users/nsanyal") # sets the given directory as the working directory
os.listdir() # lists all files in the working directory
os.makedirs("test") # create a directory named 'test' in the current wd
open("testfile.py", "w").close() # create a file named 'testfile.py' in the current wd
os.path.exists("test") # whether a directory named 'test' is in the current wd
os.path.exists("testfile.py") # whether a file named 'testfile.py' is in the current wd
\[\\[0.4in]\]
## range(0, 4)
## range(10, 13)
## (0, 3)
## (1, 6)
## (2, 9)
days = ["Monday", "Tuesday"] #can also use single quotes
items = ["Monday", 4, "Tuesday", True]
null = []
items[0] #"Monday"
items.append("Test") #["Monday", 4, "Tuesday", True, 'Test']
items += ["Test1"] #["Monday", 4, "Tuesday", True, 'Test', 'Test1']
items += "Test" #['Monday', 4, 'Tuesday', True, 'Test', 'Test1', 'T', 'e', 's', 't']
items.remove("Tuesday") #['Monday', 4, True, 'Test', 'Test1', 'T', 'e', 's', 't']
items.insert(1, "Hello") # add "Test" at index 1 #['Monday', 'Hello', 4, True, 'Test', 'Test1', 'T', 'e', 's', 't']
items1 = [items[i] for i in [0,1,4]] #['Monday', 'Hello', 'Test']
items1.sort() #['Hello', 'Monday', 'Test']
sorted(items1, key=str.lower) #['Hello', 'Monday', 'Test']
Once a tuple is created, it can’t be modified. You can’t add or remove items.
While lists allow you to create collections of values, dictionaries allow you to create collections of key / value pairs.
Sets work like tuples, but they are not ordered, and they are mutable. Or we can say they work like dictionaries, but they don’t have keys.
set1 = {"Roger", "Syd"}
set2 = {"Roger"}
intersect = set1 & set2 #{'Roger'}
union = set1 | set2 #{'Roger', 'Syd'}
difference = set1 - set2 #{'Syd'}
isSuperset = set1 > set2 # True
list(set1) #['Syd', 'Roger']
\[\\[0.4in]\]
age = 8
age += 1 # age is now 9
## other such operators: -=, *=, /=, %=, etc.
# Boolean operators: or (or |), and ( or &), not (or ~)
condition1 = True
condition2 = False
not condition1 #False
## `or` used in an expression returns the value of the first operand that is not a falsy value ( False , 0 , '' , [] ..). Otherwise it returns the last operand.
print(0 or 1) #1
## `and` only evaluates the second argument if the first one is true. So if the first argument is falsy ( False , 0 , '' , [] ..), it returns that argument. Otherwise it evaluates the second argument:
print(0 and 1) #0
# The Ternary Operator
## Instead of writing:
def is_adult(age):
if age > 18:
return True
else:
return False
## you can write
def is_adult(age):
return True if age > 18 else False
\[\\[0.4in]\]
\[\\[0.4in]\]
\[\\[0.4in]\]
def hello(name):
print('Hello ' + name + '!')
def hello(name):
if not name:
return
print('Hello ' + name + '!')
def hello(name):
print('Hello ' + name + '!')
return name, 'Roger', 8 #the return value is a tuple containing those 3 values
\[\\[0.4in]\]
class Dog: # the Dog class
def bark(self):
print('WOF!')
roger = Dog()
type(roger) #<class '__main__.Dog'>
# A Sample class with init method
class Person:
# init method or constructor
def __init__(self, name):
self.name = name
# sample method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Nikhil')
p.say_hi() #Hello, my name is Nikhil
# Inheritance
class Animal:
def walk(self):
print('Walking..')
class Dog(Animal):
def bark(self):
print('WOF!')
roger = Dog()
roger.walk() # 'Walking..'
roger.bark() # 'WOF!'
\[\\[0.4in]\]
Every Python file is a module.
import dog
dog.bark()
#or
from dog import bark # lets us pick the things we need.
bark()
# Suppose you put dog.py in a subfolder. In that folder, you need to create an empty file named __init__.py. This tells Python the folder contains modules.
from lib import dog
dog.bark()
#or
from lib.dog import bark
bark()
The Python standard library is a huge collection of all sort of utilities, ranging from math utilities to debugging to creating graphical user interfaces. The full list of standard library modules is here: https://docs.python.org/3/library/index.html. Some of the important modules are:
math
for math utilitiesre
for regular expressionsjson
to work with JSONdatetime
to work with datessqlite3
to use SQLiteos
for Operating System utilitiesrandom
for random number generation statistics for
statistics utilitiesrequests
to perform HTTP network requests http to
create HTTP serversurllib
to manage URLs\[\\[0.4in]\]
# user input
age = input()
print('Your age is ' + age)
# import module/function
import math
math.sqrt(4) # 2.0
from math import sqrt
#import data
\[\\[0.4in]\]
with
function# Instead of writing:
filename = '/Users/flavio/test.txt'
try:
file = open(filename, 'r')
content = file.read()
print(content)
finally:
file.close()
#You can write:
filename = '/Users/flavio/test.txt'
with open(filename, 'r') as file:
content = file.read()
print(content)
\[\\[0.4in]\]
You debug by adding one/more breakpoints into your code:
When the Python interpreter hits a breakpoint in your code, it will stop, and wait for your instruction.
c
to continue the execution of the program
normally.s
to step to the next line in the current
function. If the next line is a function, the debugger goes into that,
and you can then run one instruction of that function at a time.n
to step to the next line in the current
function. If the code calls functions, the debugger does not get into
them, and consider them “black boxes”.q
to stop the execution of the program.\[\\[0.4in]\]
If a function returns another function defined inside it, then the returned function has access to the variables defined in the first function even if the first function is not active any more.
def counter():
count = 0
def increment():
nonlocal count
count = count + 1
return count
return increment
increment = counter()
print(increment()) # 1
## 1
## 2
## 3
#increment() function still has access to the state of the count variable even though the counter() function has ended.
\[\\[0.4in]\]
try:
# some lines of code
try:
# some lines of code
except <ERROR1>:
# handler <ERROR1>
except <ERROR2>:
# handler <ERROR2>
except:
# catch all other exceptions
else:
# ran if no exceptions were found
finally:
# do something in any case, regardless if an error occurred or not
try:
result = 2 / 0
except ZeroDivisionError:
print('Cannot divide by zero!')
finally:
result = 1
print(result) # Cannot divide by zero! # 1
\[\\[0.4in]\]
Python defines its conventions in the PEP8 (Python Enhancement Proposals) style guide. Its full content is here: https://www.python.org/dev/peps/pep- 0008/ but here’s a quick summary of the important points to start with:
\[\\[0.4in]\]
\[\\[1in]\]