Download PyQuick MINI Documentation

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
PyQuick MINI Documentation
Release 1.0.0
Vamsi Kurama
Mar 25, 2017
Contents
1
Contents
1.1 The Basics . . . . . . . . . .
1.2 Types . . . . . . . . . . . . .
1.3 Control Flow . . . . . . . . .
1.4 Functions . . . . . . . . . . .
1.5 Modules . . . . . . . . . . .
1.6 Object Oriented Programming
1.7 Conclusion . . . . . . . . . .
1.8 Thanks . . . . . . . . . . . .
1.9 Formatting . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
1
1
4
9
13
16
18
22
22
22
2
License
23
3
Contributing
25
i
ii
CHAPTER
1
Contents
The Basics
Installation Instructions
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/
Running Python Interpreter
Python comes with an interactive interpreter. When you type python in your shell or command prompt, the python
interpreter open up with a >>> prompt and waiting for your instructions.
>>> says that your are inside the python interpreter
$ python
Python 2.7.6 (default, Apr 24 2015, 09:38:35)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
Running Python Scripts
Open your text editor, type the following text and save it as hello.py.
print "Hello, World!"
1
PyQuick MINI Documentation, Release 1.0.0
And run this program by calling python hello.py. Make sure you change to the directory where you saved the
file before doing it.
VamsiVihar:desktop ~$ python hello.py
Hello, World!
VamsiVihar:desktop ~$
Dynamically Typed
Python is a dynamic-typed language. Many other languages are static typed, such as C/C++ and Java.
A static typed language requires the programmer to explicitly tell the computer what type of “thing” each data value
is. For example, in C if you had a variable that was to contain the price of something, you would have to declare the
variable as a “float” type. This tells the compiler that the only data that can be used for that variable must be a floating
point number, i.e. a number with a decimal point. If any other data value was assigned to that variable, the compiler
would give an error when trying to compile the program.
Variables
In Python there are no declarations.
Note: Everything thing is a object in Python
Assignment
One of the most important kinds of statements in Python is the assignment statement. One of the most important kinds
of statements in Python is the assignment statement.Assignment to a variable (e.g.,name=value) is how you
create a new variable or rebind an existing variable to a new value.
The assignment statement in the simplest form has the syntax:
<variable> = <value>
<variable> = <expr>
variable is your variable to which holds the value of the expression
Indentation
Python forces the user to program in a structured format. Code blocks are determined by the amount of indentation
used.
As you’ll recall from the comparison of programming languages brackets and semicolons were used to show code
grouping or end-of-line termination for the other languages.
Python doesn’t require those, indentation is used to signify where each code block starts and ends. Whitespace is
important in Python. Actually, whitespace at the beginning of the line is important. This is called indentation. Leading
whitespace (spaces and tabs) at the beginning of the line is used to determine the indentation level of the logical line,
which in turn is used to determine the grouping of statements.
This means that statements which go together must have the same indentation. Each such set of statements is called a
block. One thing you should remember is that wrong indentation can give rise to errors. For example:
2
Chapter 1. Contents
PyQuick MINI Documentation, Release 1.0.0
Example(indent.py)
1
2
3
4
i = 5
# Error below! Notice a single space at the start of the line
print 'Value is ', i
print 'I repeat, the value is ', i
When you run this, you get the following error:
File "indent.py", line 5
print 'Value is ', i
^
IndentationError: unexpected indent
Notice that there is a single space at the beginning of the second line. The error indicated by Python tells us that the
syntax of the program is invalid i.e. the program was not properly written. What this means to you is that you cannot
arbitrarily start new blocks of statements (except for the default main block which you have been using all along, of
course). Cases where you can use new blocks will be detailed in later chapters such as the Control Flow.
How to indent ?
Use four spaces for indentation. This is the official Python language recommendation. Good editors will automatically
do this for you. Make sure you use a correct number of spaces for indentation, otherwise your program will show
errors.
Printing Output
Let’s now output some variables by assigning them some values and with some strings
Example (save it as printing.py)
1
2
3
4
5
6
7
8
i = 999
p = "PyQuick"
print(i)
print(p)
print("Hello World !!!")
print("Hello !!!")
print("Hello Python")
print("Welcome")
Output
$ python printing.py
999
PyQuickMINI
Hello World !!!
Hello !!!
Hello Python
Welcome
Input and Output
There will be situations where your program has to interact with the user. For example, you would want to take input
from the user and then print some results back. We can achieve this using the raw_input() function and print statement
respectively.
1.1. The Basics
3
PyQuick MINI Documentation, Release 1.0.0
Example (save it as input.py)
1
2
3
a = raw_input("Enter something")
print("You have entered the below")
print(a)
Output
$ python input.py
Enter something
Hello I am Your New Programming Language
You have entered the below
Hello I am Your New Programming Language
Types
Numbers
Python can handle normal long integers (max length determined based on the operating system, just like C),
Python long integers (max length dependent on available memory), floating point numbers (just like C doubles), octal
and hex numbers, and complex numbers (numbers with an imaginary component).
Generic C++ example
int a = 3; //inline initialization of integer
float b; //sequential initialization of floating point number
b = 4.0f;
Generic Python example
a = 3
b = 4.0
# Taken as Int
# Taken as Float
Note: To verify the type that’s assumed by the your interpreter use type function Eg: type(var) this returns the
type of variable
Strings
Python strings are “immutable” sequences which means they cannot be changed after they are created (Java strings
also use this immutable style). Since strings can’t be changed, we construct new strings as we go to represent computed
values.
So for example the expression (‘hello’ + ‘there’) takes in the 2 strings ‘hello’ and ‘there’ and builds a new string
‘hellothere’.
Characters in a string can be accessed using the standard [ ] syntax, and like Java and C++,
Python uses zero-based indexing, so if str is ‘hello’ str[1] is ‘e’.
If the index is out of bounds for the string, Python raises an error.
Example (save it as strings.py)
4
Chapter 1. Contents
PyQuick MINI Documentation, Release 1.0.0
1
2
#Using Single Quotes
x='Hello World'
3
4
5
#Using Double Quotes
y="Python Programming"
6
7
8
# Printing The Strings
print(x)
9
10
print(y)
Output
$ python strings.py
Hello World
Python Programming
Note: Guess the use of single Quotes and Double Quotes
slice , len()
The handy “slice” syntax (below) also works to extract any substring from a string.
var[begin:end]
The len(string) function returns the length of a string.
The [ ] syntax and the len() function actually work on any sequence type – strings, lists, etc
Example (save it as string_access.py)
1
x='Hello World'
2
3
4
#prints only the character at 0th(First) location
print x[0]
5
6
7
prints only the character at 4th location
print x[4]
8
9
10
prints the characters from 0th location to (11-1)locations
print x[0:11]
11
12
13
prints the characters till (6-1)th locations and concats Python to that
print x[:6]+"Python"
14
15
16
prints only the last character
print x[-1]
17
18
19
prints the third last character
print x[-3]
Output
$ python string_access.py
H
1.2. Types
5
PyQuick MINI Documentation, Release 1.0.0
o
Hello World
Hello Python
d
r
Lists
The most basic data structure in Python is the sequence.Each element of a sequence is assigned a number - its position
or index. The first index is zero, the second index is one,and so forth.
The list is a most versatile datatype available in Python.The list of items should be enclosed in square brackets [] so
that Python understands that you are specifying a list.The items in the list should be seperated by comma.The “empty
list” is just an empty pair of brackets [ ].
Note: Good thing about a list is that items in a list need not all have the same type.
list = ["Hello",1,True,False]
Once you have created a list, you can add, remove or search for items in the list.Since we can add and remove items,
we say that a list is a “mutable” data type i.e. this type can be altered.
Example (save it as lists.py)
1
2
# Let this be our First List
fruits = ['Mango','Apple','Banana','Orange']
3
4
5
# Let this be our Second List
vegetables = ['Brinjal','Potato','Cucumber','Cabbage','Peas']
6
7
8
# Printing Our First List
print(fruits)
9
10
11
# Printing Our Second List
print(vegetables)
$ python list.py
['Mango','Apple','Banana','Orange']
['Brinjal','Potato','Cucumber','Cabbage','Peas']
Example (save it as list_access.py)
1
2
# Let this be our First List
fruits = ['Mango','Apple','Banana','Orange']
3
4
5
# Let this be our Second List
vegetables = ['Brinjal','Potato','Cucumber','Cabbage','Peas']
6
7
8
# Zeroth Index gives us the First Element in Our List
print(vegetables[0])
9
10
11
12
# Carefully Observe the Output Indexes of the List
print(vegetables[4])
print(friuts[1])
6
Chapter 1. Contents
PyQuick MINI Documentation, Release 1.0.0
13
print(friuts[3])
14
15
# Using len() on lists
16
17
18
print(len(fruits))
print(len(vegtables))
Methods
There are lot of builtin methods.Let’s see it by Examples
Example(save it as stretch.py)
1
2
3
4
5
a = [98,76,87,45,90,23,65,2,9,20]
a.append(4)
print(a)
a.extend(b)
print(a)
Output
$ python stretch.py
[98, 76, 87, 45, 90, 23, 65, 2, 9, 20, 4]
[98, 76, 87, 45, 90, 23, 65, 2, 9, 20, 4, 123, 12]
Example (save it as see.py)
1
2
3
4
a = [98,76,87,45,90,23,65,2,9,20]
print(a.index(87))
(a.sort())
print(a)
Output
$ python see.py
2
[2, 9, 20, 23, 45, 65, 76, 87, 90, 98]
Note: To look for, the methods that are existing for a Datatype use the function dir Eg: dir(var)
Tuples
Tuples are sequences, just like lists.The only difference is that tuples can’t be changed i.e., tuples are immutable and
tuples use parentheses whereas lists are mutable and use square brackets.
Creating a tuple is as simple as putting different comma-separated values and optionally you can put these commaseparated values between parentheses also.Tuples are pretty easy to make. You give your tuple a name, then after that
the list of values it will carry.
We can access the items in the tuple by specifying the item’s position within a pair of square brackets just like we did
for lists. This is called the “indexing operator”.
For example, here we have created a variable “team” which consists of a tuple of items.
1.2. Types
7
PyQuick MINI Documentation, Release 1.0.0
“len” function can be used to get the length of the tuple. This also indicates that a tuple is a “sequence” as well.
Now if we just give the variable name “team” then we will get all the set of elements in tuple.
Example
1
2
# Let This Be Our Tuple
team = ("Sachin", "Dravid", "Dhoni", "Kohli", "Raina")
3
4
5
# It Prints All Elements In The Tuple
print(team)
$ python tuple.py
('Sachin', 'Dhoni', 'Dravid', 'Kohli', 'Raina')
1
2
# To Access The 1st Element In The Tuple
team[0]
3
4
5
# To Access The Last Element In The Tuple
team[-1]
6
7
8
# To Access The Element From 1st Location To 2nd Location
team[1:3]
$ python team_access.py
'Sachin'
'Raina'
('Sachin', 'Dhoni')
Dictionaries
A dictionary is mutable and is another container type that can store any number of Python objects, including other
container types.
Dictionaries consist of pairs (called items) of keys and their corresponding values.
Python dictionaries are also known as associative arrays or hash tables.
The general syntax of a dictionary is as follows:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
“dict” is the name of the dictionary.
It contains both the key and value pairs i.e,”Alice” is the key and “2341” is the value and the same is for next values.
You can create dictionary in the following way as well:
dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };
Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed
in curly braces.An empty dictionary without any items is written with just two curly braces, like this: {}.Keys are
unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must
be of an immutable data type such as strings, numbers, or tuples.
The main operations on a dictionary are storing a value with some key and extracting the value given the key.It is also
possible to delete a key:value pair with del.If you store using a key that is already in use, the old value associated with
that key is forgotten.It is an error to extract a value using a non-existent key.
8
Chapter 1. Contents
PyQuick MINI Documentation, Release 1.0.0
The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you
want it sorted, just apply the sorted() function to it).
To check whether a single key is in the dictionary, use the in keyword.
Accessing Values in Dictionary:
To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];
When the above code is executed, it produces the following result:
dict['Name']: Zara
dict['Age']: 7
Control Flow
Table for Quick Glance of Conditional and Control Flow Statements
Statement
if/else/elif
for
while
break, continue
pass
Role
Selection Actions
Sequence Iterations
General Loop
Loop Jumps
Empty Place Holder
Conditionals
if Tests:
One of the most common control structures you’ll use, and run into in other programs, is the if conditional block.
Simply put, you ask a yes or no question; depending on the answer different things happen.
Let’s start by getting the computer to make a simple decision. For an easy example, we will make a program to find
the largest of two numbers
Example (save it as greaterlesser.py)
1
2
3
4
5
a,b = input("Enter a,b values:")
if(a>b):
print "The largest number is",a
else:
print "The largest number is",b
Output
$ python greaterlesser.py
Enter a,b values:54 7
The largest number is 54
$ python greaterlesser.py
1.3. Control Flow
9
PyQuick MINI Documentation, Release 1.0.0
Enter a,b values:6 27
The largest number is 27
Example (save it as evenodd.py)
1
2
3
4
5
6
7
8
9
print("enter any number:")
num = input()
if(num>0):
if ((num%2)==0):
print "The entered number",num,"is even"
else:
print "The entered number",num,"is odd"
else:
print("Enter positive number")
Output
$ python evenodd.py
enter any number:7
The entered number 7 is odd
$ python evenodd.py
enter any number:54
The entered number 54 is even
Table Illustrating the syntax for all the Decision Making in Python
Simple Decision
Two Way Decision
Multiway Decision
if <condition>:
<statements>
if <condition>:
<statements>
else:
<statements>
if <condition1>:
<stametemts>
elif <condition2>:
<statements>
elif <condition3>:
<statements>
......
else:
<statements>
As we already dealt with some Simple decision and Two way decision This example shows the way for the Multiway
decision handling in Python
Looping
for loop in “python”:
The for statement in Python differs a bit from what you may be used to in C. Rather than always iterating over an
arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and
halting condition (as C),the for loop in python works a bit different.
The “for” loop in Python has the ability to iterate over the items of any sequence,such as a list or a string. As mentioned
earlier,the Python for loop is an iterator based for loop.
10
Chapter 1. Contents
PyQuick MINI Documentation, Release 1.0.0
It steps through the items in any ordered sequence list,i.e. string, lists, tuples, the keys of dictionaries and other
iterables. The Python for loop starts with the keyword “for” followed by an arbitrary variable name, which will hold
the values of the following sequence object, which is stepped through.
The general syntax of a “for” loop in “python” is as follows:
for variable in sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first.Then, the first item in the sequence is assigned to the
iterating variable ‘variable’. Next, the statements block is executed.
Each item in the list is assigned to variable, and the statement(s) block is executed until the entire sequence is exhausted. The items of the sequence object are assigned one after the other to the loop variable; to be precise the
variable points to the items.
For each item the loop body is executed.
The range() Function:
If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. The built-in function
range() is the right function to iterate over a sequence of numbers.
It generates an iterator of arithmetic progressions.range(n) generates an iterator to progress the integer numbers starting
with 1 and ending with (n -1).
To produce the list with these numbers, we have to cast rang() with the list(). range() can be called with two arguments:
range(begin,end)
Example (save it as factorial.py)
1
2
3
4
5
6
print("Enter any num:")
num = input()
fact = 1
for i in range(1,num):
fact = fact*i
print "Factorial of",num,"is:",fact
$ python factorial.py
Enter any num:6
Factorial of 6 is:720
$ python factorial.py
Enter any num:7
Factorial of 7 is:5040
The above call produces the list iterator of numbers starting with begin (inclusive) and ending with one less than the
number “end”.
while python:
A while loop statement in Python programming language repeatedly executes a target statement as long as a given
condition is true. While loops, like the ForLoop, are used for repeating sections of code - but unlike a for loop, the
while loop will not run n times, but until a defined condition is met.
The syntax of a while loop in Python programming language is:
1.3. Control Flow
11
PyQuick MINI Documentation, Release 1.0.0
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non-zero value.
The loop iterates while the condition is true. When the condition becomes false, program control passes to the line
immediately following the loop.
In Python, all the statements indented by the same number of character spaces after a programming construct are
considered to be part of a single block of code.
Python uses ** indentation ** as its method of grouping statements.
Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is
false, the loop body will be skipped and the first statement after the while loop will be executed.
Example (save it as while-factorial.py)
1
2
3
4
5
6
a = input("Enter a number")
i = fact = 1
while i<=a:
fact = fact*i
i = i+1
print(fact)
$ python while-factorial.py
Enter a Number
5
125
break
The break statement is used to break out of a loop statement i.e. stop the execution of a looping statement, even if the
loop condition has not become False or the sequence of items has not been completely iterated over.
An important note is that if you break out of a for or while loop, any corresponding loop else block is not executed.
Example (save as break.py):
1
2
3
4
5
6
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print 'Length of the string is', len(s)
print 'Done'
Output:
$ python break.py
Enter something : Programming is fun
Length of the string is 18
Enter something : When the work is done
Length of the string is 21
Enter something : if you wanna make your work also fun:
Length of the string is 37
Enter something : use Python!
12
Chapter 1. Contents
PyQuick MINI Documentation, Release 1.0.0
Length of the string is 11
Enter something : quit
Done
continue
The continue statement is used to tell Python to skip the rest of the statements in the current loop block and to continue
to the next iteration of the loop.
Example (save as continue.py):
1
2
3
4
5
6
7
8
9
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
print 'Too small'
continue
print 'Input is of sufficient length'
# Do other kinds of processing here...
Output:
1
2
3
4
5
6
7
8
$ python continue.py
Enter something : a
Too small
Enter something : 12
Too small
Enter something : abc
Input is of sufficient length
Enter something : quit
pass
pass is a null operation. when it is executed, nothing happens. It is useful as a placeholder when a statement is required
syntactically, but no code needs to be executed,
For example:
1
2
1
2
def f(arg):
pass
class C:
pass
# a function that does nothing (yet exists)
# a class with no methods (yet exists)
3
4
5
class A(ABSDBASBD,IAUSDBDBD):
pass
Functions
Function is small unit of computation which may take arguments and may return values. Function body should be
indented like if statement. Python has lot of builtin functions.
1.4. Functions
13
PyQuick MINI Documentation, Release 1.0.0
The keyword def introduces a function definition. It must be followed by the function name and the parenthesized list
of formal parameters. The statements that form the body of the function start at the next line, and must be indented.
We use def keyword to define a function. General syntax is like
The argument, params, doesn’t specify a datatype. In Python, variables are never explicitly typed. Python figures out
what type a variable is and keeps track of it internally.
1
2
3
4
def functionname(params):
statement1
statement2
.....
Simple Python Functions Illustrations
Simple Python Function taking no arguments
1
2
3
# Function to say hello on call the function
def hello():
print("Hello")
4
5
hello() # calling the function hello
Simple Python Function taking in arguments
1
2
3
# Function calculating the square of a number
def square(x):
print (x*x)
4
5
square(24) # Here the Square Function is called
Let us write a Function to add two strings and add two numbers
1
2
3
# Function Adding Numbers and Concatination of Strings
def add(x,y):
print(x+y)
4
5
add("hello","world") # Add Function is called with Two Strings
6
7
add(3,5) # Add Function is Two Numbers Here
Output
helloworld
8
Function with Default Arguments
Example (save it as func-default.py)
1
pass
pass
14
Chapter 1. Contents
PyQuick MINI Documentation, Release 1.0.0
Functions Returning Values
This illustration shows how various function in the Python script and how returned objects are assigned to variable
Example (save it as func-return.py)
1
2
3
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
4
5
6
7
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
8
9
10
11
def multiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a * b
12
13
14
15
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b
16
17
18
print "Let's do some math with just functions!"
19
20
21
22
23
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
24
25
print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)
$ python func-return.py
Let's do some math with just functions!
ADDING 30 + 5
SUBTRACTING 78 - 4
MULTIPLYING 90 * 2
DIVIDING 100 / 2
Age: 35, Height: 74, Weight: 180, IQ: 50
Main Function
Example (save it as quadratic.py)
1
import math
2
3
4
5
6
7
8
9
10
11
12
13
def main():
print "This program finds the real solutions to a quadratic\n"
a, b, c = input("Please enter the coefficients (a, b, c): ")
discrim = b * b - 4 * a * c
if discrim < 0:
print "\nThe equation has no real roots!"
elif discrim == 0:
root = -b / (2 * a)
print "\nThere is a double root at", root
else:
discRoot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discRoot) / (2 * a)
1.4. Functions
15
PyQuick MINI Documentation, Release 1.0.0
root2 = (-b - discRoot) / (2 * a)
print "\nThe solutions are:", root1, root2
14
15
16
17
18
if __name__ == "__main__":
main()
Output
$ python quadratic.py
This program finds the real solutions to a quadratic
Please enter the coefficients (a, b, c): 5,6,4
The equation has no real roots!
Recursion
One of the finest example to illustrate Recursion in any language is Fibonacci.
Example (save it as fibonacci.py)
1
2
3
4
5
6
7
8
# Functions Illustrating Fibonacci
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2) # Recursive Function Call
9
10
11
print(fibonacci(7)) # Printing the result by passing the variable 3 to the Function
˓→fibonacci
Modules
Standard Library Modules
Modules are reusable libraries of code in Python. Mostly, there are modules in the standard library and there are other
Python files, or directories containing Python files, in the current directory (each of which constitute a module).
A module is imported using the import statement.
Lets import a time module from the standard library
import time
print time.asctime()
Note: To know the list of methods and functions in a modules use the dir function
Eg: dir(time) gives out all things existing in time module
You can also do the import the either way
16
Chapter 1. Contents
PyQuick MINI Documentation, Release 1.0.0
from time import asctime
print(asctime())
Here were imported just the asctime function from the time module.
Writing Own Modules
Lets now create a simple Module that calculates the square,cube of a number
Example (save the files as sqcube.py)
1
2
def square(x):
return x * x
3
4
5
def cube(x):
return x * x * x
Now open up your interpreter and say import sqcube and use the functions in the modules
$ python
>>> import sqcube
>>> sqcube.square(25)
>>> sqcube.cube(12)
Woot! we create a python library sqcube
Third Party Modules
The python has got the greatest community for creating great python packages
Python Package is a collection of all modules connected properly into one form and distributed
PyPI, The Python Package Index maintains the list of Python packages available.
To install pip, securely download get-pip.py, from the url get-pip
Then run the following (which may require administrator access):
python get-pip.py
Find all other Installing Instruction details at https://pip.pypa.io/en/latest/installing.html
Now when you are done with pip
Go to command promt/terminal and say pip install <package_name>
Warning: Windows users make sure that you append your path variable in environment variable for your command to work
Lets now install a great package named requests and see how we can get the content of a website
pip install requests
Example (save it as requests.py)
1.5. Modules
17
PyQuick MINI Documentation, Release 1.0.0
import requests
response = requests.get('https://api.github.com/events')
response.content
Three lines of code returned the entire contents of that url.
Object Oriented Programming
A Quick Glance on the Basics on Object Orientation Terminology
class : A class is the blueprint from which individual objects are created.
object : A real World entity which have state and behavior
Lets create a class Person with a class method say in the class
1
2
3
class Person():
def say(self):
print("Hello")
Now lets create an object instance for the class person
1
2
3
class Person():
def say(self):
print("Hello")
4
5
6
jackman = Person()
jackman.say()
Extending the plot further lets us create two method hello , bye taking in arguments
1
class Person():
2
def hello(self,name):
self.name = name
print("Hello %s How are you ?"(self.name))
def bye(self,name):
self.name = name
print("Nice Meeting You %s"%(self.name))
3
4
5
6
7
8
9
10
11
12
jackman = Person()
jackman.hello("lee")
jackman.bye("edison")
Note: self is a default argument for all instance method
It’s all vague repeating the instance variable for every class method so lets create an object with the instance variables.So, its now time to work with constructors
Constructors
The Constructors in Python are written under a special method __init__.
18
Chapter 1. Contents
PyQuick MINI Documentation, Release 1.0.0
now write a constructor for an object. In this example lets create a Object with instance variables name,
year_of_birth.This process of writing a constructor in a class eliminates the repeating of instance variables for every instance method.
1
2
3
4
class Person():
def __init__(self,name,year_of_birth):
self.name = name
self.year_of_birth = year_of_birth
5
6
7
def detail(self,name):
print("Name of the person is %s"%(name))
8
9
10
def age(self,year_of_birth):
print("Your are %s Years Old"%(year_of_birth))
11
12
13
14
person = Person()
person.details()
person.age()
Classes And Objects
Let’s now to understand more about the self variable and __init__ method (Constructor) by looking at the example
below
Example (save it as bank_account.py)
1
2
3
class BankAccount:
def __init__(self):
self.balance = 0
# Creating A Class, Object & Consuctor
4
5
6
7
def withdraw(self, amount):
self.balance -= amount
return self.balance
8
9
10
11
def deposit(self, amount):
self.balance += amount
return self.balance
12
13
14
15
16
17
18
a = BankAccount()
b = BankAccount()
a.deposit(100)
b.deposit(50)
b.withdraw(10)
a.withdraw(10)
#
#
#
#
Here Instance Variable 'a' Calls The Class BankAccount
Here Instance Variable 'b' Calls The Class BankAccount
'a' Access The Methods In The Class "BankAccount"
'b' Also Access The Methods In The Class "BankAccount"
$ python bank_account.py
100
50
40
90
Single Inheritance
The Inherited class is taken as a argument to the child class.To understand clearly parent class is named Parent and
child class that inherits parent class is named Child Class.
Example (save it as SingleInheritance.py)
1.6. Object Oriented Programming
19
PyQuick MINI Documentation, Release 1.0.0
1
2
3
class Parent():
def a(self):
return self.b()
4
def b(self):
return 'Parent'
5
6
7
8
9
10
class Child(Parent):
def b(self):
return 'Child'
11
12
13
14
15
c = Parent()
d = Child()
print c.a(), d.a()
print c.b(), d.b()
$ python SingleInheritance.py
Parent, Parent
Parent, Child
Multiple Inheritance
This Example illustration the way classes are inherited in Python
Example (save it as MultipleInheritance.py)
1
2
3
class A:
def m(self):
print("m of A called")
4
5
6
7
class B(A):
def m(self):
print("m of A called")
8
9
10
11
class C(A):
def m(self):
print("m of C called")
12
13
14
15
16
17
18
class D(B,C):
def m(self):
print("m of D called")
B.m(self)
C.m(self)
A.m(self)
19
20
21
x = D()
x.m()
Output
$
m
m
m
m
python MultipleInheritance.py
of D called
of B called
of C called
of A called
20
Chapter 1. Contents
PyQuick MINI Documentation, Release 1.0.0
Exception Handling
Handling Various Exceptions in Python.
Look at the following code and observe when the Exceptions are raised.
Example (save it as exception.py)
1
r = [7, 54, 27, 6]
2
3
4
# This prints the 1st index element
print(r[0])
5
6
7
# This raises IndexError since list contains only 4 elements
print(r[5])
8
9
s = {'a':1, 'b':2, 'c'=3}
10
11
12
# This prints the value hold by 'b' in the list
print(s[b])
13
14
15
# This raises the KeyError since d-key is not present in the list
print(s[d])
Output
$ python exception.py
7
IndexError: List index out of range
2
KeyError: 'd'
Now let’s Handle the above exceptions raised in the above examples
Example (save it as indexerror.py)
1
try:
2
r = [7, 54, 27, 6]
print(r[5])
except IndexError as e:
print(e)
finally:
print("End Of Index Error")
3
4
5
6
7
Output
$ python indexerror.py
list index out of range
End Of Index Error
Example (save it as keyerror.py)
1
try:
2
s = {'a':1, 'b':2, 'c'=3}
print(s[d])
except KeyError as e:
print(e)
finally:
print("End Of Key Error")
3
4
5
6
7
1.6. Object Oriented Programming
21
PyQuick MINI Documentation, Release 1.0.0
Output
$ python keyerror.py
'd'
End Of Key Error
Note: The exceptions in the above programs are purposefully raised to illustrate Exception Handling
Conclusion
Feel free to let me know if you have any suggestions to improve the book as well. Copyright (c) 2014 Copyright Vamsi
Kurama All Rights Reserved.
Thanks
First of all, I’d like to say thanks two people. When I started this book I was alone. As a part of the Python users group
activity we were flying across various places to meet people. There I met a few interestingly. After a period of time out
of those few, two people who were unknown to me came forward and helped me in writing drafts and code samples for
this miniature. And after all those two people Prasanthi and Sindhu were now great friends for me. PyQuick wouldn’t
be happening if their support lacks. I’m looking forward to work with them to manage the project into the future.
Another big thanks to father, mother and brother who always supported in making my things happen and, being patient
with me during late nights.
Formatting
Footnotes will be used for citations so you don’t think I’m making things up.
Italic text will be used to denote a file name.
Bold text will be used to denote a new or important term.
Warning: Common pitfalls that could cause major problems will be shown in a warning box.
Note: Supplemental information will appear in note boxes.
22
Chapter 1. Contents
CHAPTER
2
License
In the spirit of open source software, I’m placing all of the content in this book in the public domain.
Have fun with it.
23
PyQuick MINI Documentation, Release 1.0.0
24
Chapter 2. License
CHAPTER
3
Contributing
The project is hosted on GitHub and pull requests are welcome!
25