Friday, September 30, 2011

Flow Charting Tools : Free and Open Source

The flowchart is a means of visually presenting the flow of data through an information processing systems, the operations performed within the system and the sequence in which they are performed. In this lesson, we shall concern ourselves with the program flowchart, which describes what operations (and in what sequence) are required to solve a given problem.


The program flowchart can be likened to the blueprint of a building. As we know a designer draws a blueprint before starting construction on a building. Similarly, a programmer prefers to draw a flowchart prior to writing a computer program.


American National Standard Flow Chart Symbols


Gliffy is a free web-based diagram editor to create, share, and collaborate on a wide range of diagrams.
http://www.gliffy.com/


Project Draw is a free web-based diagram editor to create basic network, flowchart or quick form layout diagrams.
http://draw.labs.autodesk.com/ADDraw/draw.html


DIA is a desktop application on Windows and Linux to draw E-R diagrams, flowcharts.
http://live.gnome.org/Dia




MEANING OF A FLOWCHART


  • A flowchart is a diagrammatic representation that illustrates the sequence of operations to be performed to get the solution of a problem.
  • Flowcharts are generally drawn in the early stages of formulating computer solutions. Flowcharts facilitate communication between programmers and business people.
  • Flowcharts play a vital role in the programming of a problem and are quite helpful in understanding the logic of complicated and lengthy problems.
  • Once the flowchart is drawn, it becomes easy to write the program in any high level language. Often we see how flowcharts are helpful in explaining the program to others.
  • Flowchart is a must for the better documentation of a complex program.

    Examples


    Source : eDrawSoft

Thursday, August 4, 2011

Step By Step Programing to Teach Python



Step By Step Programing to Learn Python

Used to explain syntax elements typically starts with a programming example. This example is then stepped through line by line which illustrates the evaluation of expressions.


Type 1.1
Input fix, Output fix, max. one step per line FindError locate error in source code

Type 2.1
1. Step: find erroneous line, 2. Step: Dialog with different possible explanations for the error, max.


Type 3.1
For a given output the user has to find the adequate initialization of a variable.


Type 3.2
User initializes Variable, finds the correct output from a collection of (five) answers


Type 3.3
A variable is initialized randomly and the user has to find the output from a List of answers


Type 3.4
A variable is initialized randomly and the user has to type in the output of the program


Type 3.5
Program is fixed, user gives output of the program in text input dialog

Type 3.6 Program is fixed, user gives output of the program in check box dialog,

Type 4.1
A line of Code is missing. The user has to point to where to insert the line. A list of 5 possibilities is given to chose from.


Type 4.2
A line of Code is missing. The user has to point to where to insert the line. The user has to type in the missing line.


Source
INTERACTIVE LEARNING OBJECTS: A FRAMEWORK BASED APPROACH:
Friedbert KasparUniversity of Applied ScienceFaculty of Computer Science

http://www.codewitz.net/papers/MMT_32-36_Friedbert_Kaspar.pdf

Monday, July 25, 2011

Python Recursion

#!/usr/bin/python

def factorial(n):
    space = '*' * (4 * n)
    print space, 'factorial', n
    if n == 0:
        print space, 'returning 1'
        return 1
    else:
        recurse = factorial(n-1)
        result = n * recurse
        print space, 'returning', result
        return result

x=factorial(3)
print x

----
Draw a flow chart for this program
What if we change x=factorial(3) to x=factorial(5)
Change the flow chart

Python Data Types Code Example - පයිතන් දත්ත වර්ග

x = []
for i in range(0,10):
    x.append(i)
print x
print "______________________________________"

y = x * 10

x = "Hello World!"

print x
print "______________________________________"
print y

# What are X and Y?

===================================



#############
# Arithmetic
#############
4 + 4 == 8
3 - 5 == -2
16 / 2 == 8
16 * 4 == 64
3 % 2 == 1 # Modulus

# Long Int Conversion - Useful for function type mismatches - Not needed here.
100000000000000000000L + long(100) == 100000000000000000100L

======================

##########
# Strings
##########

a = "Hello"
b = "World!"

# Concatenation
a + " " + b == "Hello World!"

# Repetition and Concatenation
a * 3 + " " + b == "HelloHelloHello World!"
(a + " ") * 3 + b == "Hello Hello Hello World!"

# Indexing
b[2] == "r"

# Conversion of data to string - Sesame Street:
c = 7 # Backquote ` ` or str() operations
( a + " number " + `c` ) and ( a + " number " + str(c) ) == "Hello number 7"


============================




Python dice roll code example

#dice roll function (6-sided by default)
import random

def roll(d=6):
     return random.randint(1, d)
while 1 > 0 :
   
    a=raw_input("enter number 1-6 : ")
    b=int(a)
    print ("entered :" , b)
    c=roll()
    print ("received :" , c)
    if (c == b):
        print ("you win ")
        break
    else :
        print ("you loose " , b , " <> ", c)
        print ("---------------------")



what does break do?
What is the use of random ?

======================

Python Dictionaries and Lists Difference

#debugger example

print "This function creates a list."

def makelist():
    a = [] # list
    for i in range(1, 20):
        a.append(i)
        print "appending", i
        print "now list", a
    return a

def printlist(a):
    for i in a:
        print i,

b=makelist()
printlist(b)



#Dictionaries

#rock, paper, scissors game using dictionary

choice = raw_input("Enter s, r, or p: ")
results = {"s": "cut paper", "r": "crushes scissors", "p":  
    "covers rock"}
print choice, results[choice]

#
#

Python Classes Revision

#class example
class Student:
    def __init__(self, myname, myage):  # note double underscores
        self.myname = myname                 
# take passed value to a var
        self.myage = myage                   # take next value
    def sayname(self):                            # take next function in class
        print "Hello, my name is", self.myname

    def sayage(self):
        print "Hello, my age is", self.myage

    def jump(self,jump):  # the jump function
        if (jump > 0) :
            print "I am jumping up ", jump
        else :
            print "I am jumping down ", jump

name1 = Student("Amara", 17) # create object from class
name1.sayname() # print name
name1.sayage()
name1.jump(4) # move up 4
name1.jump(- 4)
# move down 4

Python Lists : Code Examples for learning

print "This function creates a list."
def makelist():
    a = []
    for i in range(1, 20):
        a.append(i)
        print ("appending", i, ":", a)
    return a
makelist()

How does this work?

hints

First you create and empty list and fill it later []
you add item one by one - it get added to last

Why lists are powerful than tuples
What is the advantage of dictioneries?
Can you have a tuple and a dictionary in a list?
Can you also add an  object to it?


#building a list from another list
L1 = ['spa', 'spa', 'spa', 'beans', None, 'spa', 'spa']
L2 = []
for i in L1:
    if i is not None:
        L2.append(i)
print (L2)
#
#




What is the output of phyton from code

What is the output of phyton

# mile/kilometer conversion
for miles in range(10, 70, 10):
    km = miles * 1.609
    print "%d miles --> %3.2f kilometers" % (miles, km)

#

Hints
range work among all numbers
multiplication by float number create float variable
%d digit   %f float


=============
How do you call tiny function

def simplefunction(x):
    print ("functions work!")
    print ("You passed parameter", x)
    z = x**2
    print (x, "squared value =", z)
    return z

Hints
functions need to be called form program to work
some functions need parameters
what error would you get if you call it
simplefunction()
or
simplefunction("Kandy")

======================

What happens here ?

#while loop example
countdown = 10
while countdown:
    print countdown,
    countdown -= 1
print "blasted!"

#

explain each line to your self ?
how many times will the loop run ?
what is the value of countdown at last ?

Python Code Completion Exersize

පන්තියක සිසුන් විෂය තුනක් සඳහා ලබාගත් ලකුණු එක් එක් සිසුවාගේ නම සමග පහතදැක්වෙන අයුරු "input.text" නම් ගොනුවේ සටහන් කර ඇත.

Nimal, 20, 10, 30
Saman, 40, 60, 45
Mala, 22, 65, 75

එක් එක් සිසුවා විෂය තුන සඳහා ලබාගත් ලකුණුවල එකතුව හා මධ්‍යන්‍යය (Mean) පහත දැක්වෙන ආකාරයට ආදානය කළ යුතු යැයි සලකන්න.

1. Nimal 60 20.0
2. Saman 145 48.3
3. Mala 162 54.0

මේ සඳහා නිර්මාණය කළ අසම්පූර්ණ පයිතන් කේතයක් පහත දැක්වේ. මෙම කේතයේ සම්පූර්ණ ස්ථාන කඩ ඉරි මගින් දක්වා ඇත.

def total(marks):
#compute the total
    total=0
    for mark in marks
        _ _ _ _ _ _ _ _ _
return total

f=open("inpit.text")
line=f.readline()
i= _ _ _ _ _ _ _ _ _ _
while(line ='')
    record=line.strip('\n').split(",")
    aggregate=total_ _ _ _ _ _ _ _ _ _
    print i,_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    i +=1
    line = _ _ _ _ _ _ _ _ _
f.close()

ඉහත කේතයට අදාළ ප‍්‍රතිදානය ලබාගැනීම සඳහා සුදුසු ලෙස සම්පූර්ණ කරන්න.

def total(marks):  #compute the total
    total=0
    for mark in marks
        total=total+marks
return total

f=open("input.text")
line=f.readline()
i=1
while(line <> '') :
     record=line.split(",")
     total=record[1]+record[2] + record[3]
     aggregate=total/3
     print ("%. %s %d, f%") % (i,record[1], total, aggregate)
     i +=1
     line =line=f.readline()
f.close()


=====

The Mean and the Median

100, 100, 130, 140, 150

To find the median, arrange values from smallest to largest.

If there is an odd number of values, the median is the middle value. If there is an even number of values, the median is the average of the two middle values.

130 is the middle value.


The mean is computed by adding all of the observations and dividing by the number of observations.

 (100 + 100 + 130 + 140 + 150)/5 = 620/5 = 124

Population mean = μ = ΣX / N     OR   
Sample mean = x = Σx / n


Four friends take an IQ test. Their scores are 96, 100, 106, 114. Which of the following statements is true?

I. The mean is 103.
II. The mean is 104.
III. The median is 100.
IV. The median is 106.

(A) I only
(B) II only
(C) III only
(D) IV only
(E) None is true

Solution

The correct answer is (B).

Mean score = Σx / n = (96 + 100 + 106 + 114) / 4 = 104

Since there are an even number of scores (4), the median is the average of the two middle scores. Thus, the median is (100 + 106) / 2 = 103.
------------------------------------------

http://stattrek.com/lesson1/formulas.aspx

Code Correction

පහත පයිතන් ක‍්‍රමලේඛ අතුරින් දෝෂ රහිත ක‍්‍රමලේඛ මොනවාදැයි දක්වන්න. දෝෂ රහිත ක‍්‍රමලේඛ ක‍්‍රියාත්මක කිරීමේදී ලැබෙන ප‍්‍රතිදාන මොනවාදැයි දක්වන්න.


දෝෂ සහිත ක‍්‍රමලේඛ නිදොස් කර දක්වා, එම නිදොස් ක‍්‍රමලේඛ ක‍්‍රියාත්මක කිරීමේදී ලැබෙන ප‍්‍රතිදාන මොනවාදැයි සඳහන් කරන්න.

animals=['Dog','Rat','Cat']
animals.sort()
for animal in animals:
print i,animal.strip(),len(animal)
i t=1

animals=['Dog','Rat','Cat']
animals.sort()
for animal in animals:
    i=len(animal)
    t=animal.strip(),
    print (t)



def times(a):
for i in range(1,12):
print a,' x ', i,' = ',a*i
times(5)



def times(a):
    for i in range(1,12):
          print (a, i,' = ',a*i)

times(5)

===

string -- Common string operations


This module defines some constants useful for checking character classes and some useful string functions. See the module re for string functions based on regular expressions.
The constants defined in this module are:

ascii_letters
The concatenation of the ascii_lowercase and ascii_uppercase constants described below. This value is not locale-dependent.

ascii_lowercase
The lowercase letters 'abcdefghijklmnopqrstuvwxyz'. This value is not locale-dependent and will not change.

ascii_uppercase
The uppercase letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. This value is not locale-dependent and will not change.

digits
The string '0123456789'.

hexdigits
The string '0123456789abcdefABCDEF'.

letters
The concatenation of the strings lowercase and uppercase described below. The specific value is locale-dependent, and will be updated when locale.setlocale() is called.

lowercase
A string containing all the characters that are considered lowercase letters. On most systems this is the string 'abcdefghijklmnopqrstuvwxyz'. Do not change its definition -- the effect on the routines upper() and swapcase() is undefined. The specific value is locale-dependent, and will be updated when locale.setlocale() is called.

octdigits
The string '01234567'.

punctuation
String of ASCII characters which are considered punctuation characters in the "C" locale.

printable
String of characters which are considered printable. This is a combination of digits, letters, punctuation, and whitespace.

uppercase
A string containing all the characters that are considered uppercase letters. On most systems this is the string 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. Do not change its definition -- the effect on the routines lower() and swapcase() is undefined. The specific value is locale-dependent, and will be updated when locale.setlocale() is called.

whitespace
A string containing all characters that are considered whitespace. On most systems this includes the characters space, tab, linefeed, return, formfeed, and vertical tab. Do not change its definition -- the effect on the routines strip() and split() is undefined.
Many of the functions provided by this module are also defined as methods of string and Unicode objects; see ``String Methods'' (section 2.2.6) for more information on those. The functions defined in this module are:

atof( s)
Deprecated since release 2.0. Use the float() built-in function.
Convert a string to a floating point number. The string must have the standard syntax for a floating point literal in Python, optionally preceded by a sign ("+" or "-"). Note that this behaves identical to the built-in function float()  when passed a string. Note: When passing in a string, values for NaN  and Infinity may be returned, depending on the underlying C library. The specific set of strings accepted which cause these values to be returned depends entirely on the C library and is known to vary.

atoi( s[, base])
Deprecated since release 2.0. Use the int() built-in function.
Convert string s to an integer in the given base. The string must consist of one or more digits, optionally preceded by a sign ("+" or "-"). The base defaults to 10. If it is 0, a default base is chosen depending on the leading characters of the string (after stripping the sign): "0x" or "0X" means 16, "0" means 8, anything else means 10. If base is 16, a leading "0x" or "0X" is always accepted, though not required. This behaves identically to the built-in function int() when passed a string. (Also note: for a more flexible interpretation of numeric literals, use the built-in function eval() .)

atol( s[, base])
Deprecated since release 2.0. Use the long() built-in function.
Convert string s to a long integer in the given base. The string must consist of one or more digits, optionally preceded by a sign ("+" or "-"). The base argument has the same meaning as for atoi(). A trailing "l" or "L" is not allowed, except if the base is 0. Note that when invoked without base or with base set to 10, this behaves identical to the built-in function long()  when passed a string.

capitalize( word)
Return a copy of word with only its first character capitalized.

capwords( s)
Split the argument into words using split(), capitalize each word using capitalize(), and join the capitalized words using join(). Note that this replaces runs of whitespace characters by a single space, and removes leading and trailing whitespace.

expandtabs( s[, tabsize])
Expand tabs in a string, i.e. replace them by one or more spaces, depending on the current column and the given tab size. The column number is reset to zero after each newline occurring in the string. This doesn't understand other non-printing characters or escape sequences. The tab size defaults to 8.

find( s, sub[, start[,end]])
Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.

rfind( s, sub[, start[, end]])
Like find() but find the highest index.

index( s, sub[, start[, end]])
Like find() but raise ValueError when the substring is not found.

rindex( s, sub[, start[, end]])
Like rfind() but raise ValueError when the substring is not found.

count( s, sub[, start[, end]])
Return the number of (non-overlapping) occurrences of substring sub in string s[start:end]. Defaults for start and end and interpretation of negative values are the same as for slices.

lower( s)
Return a copy of s, but with upper case letters converted to lower case.

maketrans( from, to)
Return a translation table suitable for passing to translate() or regex.compile(), that will map each character in from into the character at the same position in to; from and to must have the same length. Warning: Don't use strings derived from lowercase and uppercase as arguments; in some locales, these don't have the same length. For case conversions, always use lower() and upper().

split( s[, sep[, maxsplit]])
Return a list of the words of the string s. If the optional second argument sep is absent or None, the words are separated by arbitrary strings of whitespace characters (space, tab, newline, return, formfeed). If the second argument sep is present and not None, it specifies a string to be used as the word separator. The returned list will then have one more item than the number of non-overlapping occurrences of the separator in the string. The optional third argument maxsplit defaults to 0. If it is nonzero, at most maxsplit number of splits occur, and the remainder of the string is returned as the final element of the list (thus, the list will have at most maxsplit+1 elements).

splitfields( s[, sep[, maxsplit]])
This function behaves identically to split(). (In the past, split() was only used with one argument, while splitfields() was only used with two arguments.)

join( words[, sep])
Concatenate a list or tuple of words with intervening occurrences of sep. The default value for sep is a single space character. It is always true that "string.join(string.split(s, sep), sep)" equals s.

joinfields( words[, sep])
This function behaves identically to join(). (In the past, join() was only used with one argument, while joinfields() was only used with two arguments.) Note that there is no joinfields() method on string objects; use the join() method instead.

lstrip( s[, chars])
Return a copy of the string with leading characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the beginning of the string this method is called on. Changed in version 2.2.3: The chars parameter was added. The chars parameter cannot be passed in earlier 2.2 versions.

rstrip( s[, chars])
Return a copy of the string with trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the end of the string this method is called on. Changed in version 2.2.3: The chars parameter was added. The chars parameter cannot be passed in 2.2 versions.

strip( s[, chars])
Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on. Changed in version 2.2.3: The chars parameter was added. The chars parameter cannot be passed in earlier 2.2 versions.

swapcase( s)
Return a copy of s, but with lower case letters converted to upper case and vice versa.

translate( s, table[, deletechars])
Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal.

upper( s)
Return a copy of s, but with lower case letters converted to upper case.

ljust( s, width)
rjust( s, width)
center( s, width)
These functions respectively left-justify, right-justify and center a string in a field of given width. They return a string that is at least width characters wide, created by padding the string s with spaces until the given width on the right, left or both sides. The string is never truncated.

zfill( s, width)
Pad a numeric string on the left with zero digits until the given width is reached. Strings starting with a sign are handled correctly.

replace( str, old, new[, maxsplit])
Return a copy of string str with all occurrences of substring old replaced by new. If the optional argument maxsplit is given, the first maxsplit occurrences are replaced.

math -- Mathematical functions

This module is always available. It provides access to the mathematical functions defined by the C standard. These functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for complex numbers. The distinction between functions which support complex numbers and those which don't is made since most users do not want to learn quite as much mathematics as required to understand complex numbers. Receiving an exception instead of a complex result allows earlier detection of the unexpected complex number used as a parameter, so that the programmer can determine how and why it was generated in the first place. The following functions are provided by this module. Except when explicitly noted otherwise, all return values are floats:
acos( x)
Return the arc cosine of x.

asin( x)
Return the arc sine of x.

atan( x)
Return the arc tangent of x.

atan2( y, x)
Return atan(y / x).

ceil( x)
Return the ceiling of x as a float.

cos( x)
Return the cosine of x.

cosh( x)
Return the hyperbolic cosine of x.

degrees( x)
Converts angle x from radians to degrees.

exp( x)
Return e**x.

fabs( x)
Return the absolute value of x.

floor( x)
Return the floor of x as a float.

fmod( x, y)
Return fmod(x, y), as defined by the platform C library. Note that the Python expression x % y may not return the same result.

frexp( x)
Return the mantissa and exponent of x as the pair (m, e). m is a float and e is an integer such that x == m * 2**e. If x is zero, returns (0.0, 0), otherwise 0.5 <= abs(m) < 1.

hypot( x, y)
Return the Euclidean distance, sqrt(x*x + y*y).

ldexp( x, i)
Return x * (2**i).

log( x[, base])
Returns the logarithm of x to the given base. If the base is not specified, returns the natural logarithm of x. Changed in version 2.3: base argument added.

log10( x)
Return the base-10 logarithm of x.

modf( x)
Return the fractional and integer parts of x. Both results carry the sign of x. The integer part is returned as a float.

pow( x, y)
Return x**y.

radians( x)
Converts angle x from degrees to radians.

sin( x)
Return the sine of x.

sinh( x)
Return the hyperbolic sine of x.

sqrt( x)
Return the square root of x.

tan( x)
Return the tangent of x.

tanh( x)
Return the hyperbolic tangent of x.
Note that frexp() and modf() have a different call/return pattern than their C equivalents: they take a single argument and return a pair of values, rather than returning their second return value through an `output parameter' (there is no such thing in Python).
The module also defines two mathematical constants:

pi
The mathematical constant pi.

e
The mathematical constant e.

Interpreters and Compilers Differences

භාෂා සම්පාදකවල (Compilers) හා අර්ථ වින්‍යාසකවල(Interpreters) මූලික කාර්යය කුමක්දැයි දක්වා, ඒවා භාවිතයේදී ලැබෙන වාසි සහ අවාසි සන්සන්දනය කරන්න.

Compiler vs Interpreter
Both basically serve the same purpose.
Convert one level of language to another level.

Compiler converts the high level instructions into machine language.

Interpreter converts the high level instruction into an intermediate form, and the instructions are executed.

Compiler
Convert to binary form understood by the computer.

The complier programs are evolving in this way which improves their ease of use.

Compliers can be multiple or multistage pass. The first pass can convert the high level language into a language that is closer to computer language. Then the further passes can convert it into final stage for the purpose of execution.

The advantage of using an interpreter is that the high level instruction does not goes through compilation stage which can be a time consuming method.

Almost all high level programming languages have compilers and interpreters.

Difference between compiler and interpreter

• A complier converts the high level instruction into machine language
• Interpreter converts the high level instruction into an intermediate form.

• Before execution, entire program is executed by the compiler

interpreter translates a line then executes it and so on.

• List of errors is created by the compiler after the compilation process

• interpreter stops translating after the first error.

• Compiler creates an independent executable file

• interpreter is required by an interpreted program each time.

Assembler

Dual Purpose
Java
C++
Python
VB
ASP.NET

Interpreter
PHP
ASP
Java Script

Flow Chart to Python Code

(python)
x=1
total=0
while x<=10 :
    math=input("enter marks")
    x=x+1
    total=total+math

avg=total/x-1
if (avg > 50):
   print "Good"
else:
  print "Bad"


Python Code

x=1

total=0
while x<=10 :
    xmath=int(input("enter marks"))
    type(xmath)
    x=x+1
    total=total+xmath

avg=(total/x-1)

if (avg > 50):
   print ("Good")
else:
  print ("Bad")

======================

ffor x in "python-programming":
    print(x)
    if x=='-':
        break
            print x

What is your explanation - will this work ? on indentinng

what are the output of following codes ?

for x in "python-programming":
    print(x)
    if x=='-':
        break
        print (x)

for x in "python-programming":
    print(x)
    if x=='-':
        continue
        print (x)

පහත දැක්වෙන පයිතන් ක‍්‍රමලේඛය සලකා බලන්න:

පහත දැක්වෙන පයිතන් ක‍්‍රමලේඛය සලකා බලන්න:

from date import date
class dtcheck:
def_init_(self,y,m,d):
     self.now=date.today()   
     self.dob=date(y,m,d)
     self.age=self.now - self.dob

def printage(self):
      return "your age %d" % ((self.age.days)/365)


මෙහි දැක්වෙන්නේ උපන් දිනය ලබාදීමෙන් පසු වයස අවුරුදුවලින් ප‍්‍රතිපානය කිරීම සඳහා සැකසූ පන්ති මොඩියුලයකි. මෙම මොඩියුලය "dcheck.py" යන ලිපිගොනු නාමයෙන් පයිතන් ක‍්‍රමලේඛයක් ලෙස සුරැකී ඇත. මෙම පන්ති මොඩියුලයෙන් වස්තුවක් (object) නිර්මාණය කර, එයට ආදානය ලබාදෙමින් ප‍්‍රතිදානය ලබාගැනීමට භාවිත කළ හැකි නිවැරදිථ පයිතන් මොඩියුලය කුමක් ද?


import dcheck
w=dcheck.dtcheck(1976,11,10)
result=w.printage()
print w


import dcheck
w.dcheck(1976/11/10)
result=w.printage()
print result
 

import dcheck
u=dcheck.dtcheck(1976,11,10)
print u.printage()

import dcheck
w.dtcheck.dcheck(1976,11,10)
result=w.printage()
print result


w=dcheck.dcheck(1976/11/10)
result=w.printage()
print result 



Python 3.x code

from datetime import date


class dtcheck:
    def __init__(self,y,m,d):
        self.now=date.today()
        self.dob=date(y,m,d)
        self.age=self.now - self.dob
       
    def printage(self):
        return "your age %d"%((self.age.days)/365)

import dcheck
u=dcheck.dtcheck(1976,11,10)
print (u.printage())





================

The import Statement:

You can use any Python source file as a module by executing an import statement in some other Python source file. import has the following syntax:
import module1[, module2[,... moduleN]

# Import module hello
import hello # Now you can call defined function

hello.print_func("Dinuka")

Hello : Dinuka

The from...import * Statement:

It is also possible to import all names from a module

from modname import *

The PYTHONPATH Variable:

The PYTHONPATH is an environment variable, consist list of directories.

set PYTHONPATH=c:\python20\lib;
UNIX system:
set PYTHONPATH=/usr/local/lib/python

#!/usr/bin/python 

=================

Namespaces and Scoping:

Variables are names map to objects.

A namespace is a dictionary of variable names (keys) and their corresponding objects (values).

Python can access variables in a local namespace and in the global namespace. I

if a local and a global variable have the same name, the local variable shadows the global variable.

Each function has its own local namespace.

Python makes guesses on whether variables are local or global.

It assumes that any variable assigned a value in a function is local.

To assign a value to a global variable within a function,

use global VarName which tells Python that VarName is a global variable.


#!/usr/bin/python

Honey = 2000
def AddHoney():
   # Uncomment the following line to fix the code:
   # global Honey
   Honey = Honey + 1

print Honey
AddHoney()
print Honey


 what happens ? if  # global Honey uncommented like
global Honey

The Global variable get updated
=================

Packages in Python:

A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages,

Example:

Consider a file Mobs.py available in Phone directory. This file has following line of source code:
#!/usr/bin/python

def Mobs():
   print "I'm a mobile phone"
Similar way we have another two files having different functions with the same name as above:
  • Phone/Isdn.py file having function Isdn()
  • Phone/G3.py file having function G3()
Now create one more file __init__.py in Phone directory :
  • Phone/__init__.py
To make all of your functions available when you've imported Phone, you need to put explicit import statements in __init__.py as follows:
from Pots import Pots
from Isdn import Isdn
from G3 import G3
After you've added these lines to __init__.py, you have all of these classes available when you've imported the Phone package:

#!/usr/bin/python

# Now import your Phone Package.
import Phone

Phone.Mobs()
Phone.Isdn()
Phone.G3()
This would produce following result:
I'm a mobile phone
I'm 3G Phone
I'm ISDN Phone


Python Operators

3 = 1+2
in 1 + 2 =3 , 1 and 2 are called operands and + is called operator.  

  • Arithmetic Operators   +, - , /
  • Comparision Operators  <>
  • Logical (or Relational) Operators  or and
  • Assignment Operators =
  • Conditional (or ternary) Operators
Lets have a look on all operators one by one.

Python Arithmetic Operators:

Assume variable a holds 10 and variable b holds 20 then:
Operator Description Example
+ Addition - Adds values on either side of the operator a + b will give 30
- Subtraction - Subtracts right hand operand from left hand operand a - b will give -10
* Multiplication - Multiplies values on either side of the operator a * b will give 200
/ Division - Divides left hand operand by right hand operand b / a will give 2
% Modulus - Divides left hand operand by right hand operand and returns remainder b % a will give 0
** Exponent - Performs exponential (power) calculation on operators a**b will give 10 to the power 20
// Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. 9//2 is equal to 4 and 9.0//2.0 is equal to 4.0

Python Comparison Operators:

Assume variable a holds 10 and variable b holds 20 then:
Operator Description Example
== Checks if the value of two operands are equal or not, if yes then condition becomes true. (a == b) is not true.
!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (a != b) is true.
<> Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (a <> b) is true. This is similar to != operator.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (a > b) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (a < b) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (a >= b) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (a <= b) is true.

Python Assignment Operators:



Python Logical Operators:


and Logical AND operator.
If both the operands are true then condition becomes true.
(a and b) is true.
or Logical OR Operator. I
f any of the two operands are non zero then then condition becomes true.
(a or b) is true.
not Logical NOT Operator.
Use to reverses the logical state of its operand.
If a condition is true then Logical NOT operator will make false.
not(a and b) is false.





Python Membership Operators:

Operator Description Example
in Evaluates to true if it finds a variable in the specified sequence and false otherwise. x in y, here in results in a 1 if x is a member of sequence y.
not in Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. x not in y, here not in results in a 1 if x is a member of sequence y.

Python Assignment Operators:

Assume variable a holds 10 and variable b holds 20 then:
Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left side operand c = a + b will assigne value of a + b into c
+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c - a
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a
/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand c /= a is equivalent to c = c / a
%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a
**= Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand c **= a is equivalent to c = c ** a
//= Floor Dividion and assigns a value, Performs floor division on operators and assign value to the left operand c //= a is equivalent to c = c // a

Python Comparison Operators:

Assume variable a holds 10 and variable b holds 20 then:
Operator Description Example
== Checks if the value of two operands are equal or not, if yes then condition becomes true. (a == b) is not true.
!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (a != b) is true.
<> Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (a <> b) is true. This is similar to != operator.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (a > b) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (a < b) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (a >= b) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (a <= b) is true.

Python Arithmetic Operators:

Assume variable a holds 10 and variable b holds 20 then:
Operator Description Example
+ Addition - Adds values on either side of the operator a + b will give 30
- Subtraction - Subtracts right hand operand from left hand operand a - b will give -10
* Multiplication - Multiplies values on either side of the operator a * b will give 200
/ Division - Divides left hand operand by right hand operand b / a will give 2
% Modulus - Divides left hand operand by right hand operand and returns remainder b % a will give 0
** Exponent - Performs exponential (power) calculation on operators a**b will give 10 to the power 20
// Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. 9//2 is equal to 4 and 9.0//2.0 is equal to 4.0
 
 

Python Bitwise Operators:

Bitwise operator works on bits and perform bit by bit operation.
Assume if a = 60; and b = 13; Now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a  = 1100 0011

There are following Bitwise operators supported by Python language
Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both operands. (a & b) will give 12 which is 0000 1100
| Binary OR Operator copies a bit if it exists in eather operand. (a | b) will give 61 which is 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand but not both. (a ^ b) will give 49 which is 0011 0001
~ Binary Ones Complement Operator is unary and has the efect of 'flipping' bits. (~a ) will give -60 which is 1100 0011
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. a << 2 will give 240 which is 1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. a >> 2 will give 15 which is 0000 1111

Python syntax examples

පහත දැක්වෙන පයිතන් ප‍්‍රකාශ සලකා බලන්න:


A - s="It's correct"

B - x=y=z=2.5

C - x,y,z=1,2.3,'string'

D - #This is not correct

E - a=['string',123]
F - b=5
while 4<=b>10:
b+=1
G - for x in range(0,12,3):
print x
H - a={'a':'b',4:40}
I - def fun1(a,b=4,l=[]):
return b*a


==================



Reserved Words:

The following list shows the reserved words in Python. These reserved words may not be used as constant or variable or any other identifier names.
Keywords contain lowercase letters only.
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield



Multi-Line Statements:

Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example:
total = item_one + \
        item_two + \
        item_three
word = 'word'
sentence = "isn't this a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
paragraph = '''This is a paragraph. It is
made up of multiple lines and sentences.'''



# This is a comment.
# This is a comment, too.

raw_input("\n\nPress the enter key to exit.")
input("\n\nPress the enter key to exit.")
print("Press the enter key to exit") # Python 3.x
print "Press the enter key to exit" # Python 2.x
var1 = 1
var2 = 10
del var1, var2
Strings
var1 = 'Hello World!'
var2 = "Python Programming"

print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]


var1 = 'Hello World!'
print "Updated String :- ", var1[:6] + 'Python'
\n 0x0a Newline
a holds 'Hello' and b holds 'Python'  then:

 
print ("My name is %s and weight is %d kg!" % ('Sinali', 21) 
This will produce following result:
My name is Zara and weight is 21 kg!

Format Symbol Conversion
%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase 'e')
%E exponential notation (with UPPERcase 'E')
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E

Unicode String:

print u'Hello, world!'
This would print following result:
Hello, world!

count = 0 

while (count < 9):
      print 'The count is:', count
      count = count + 1
      print "Good bye!"


for letter in 'Python':     # First Example
   if letter == 'h':
      break
   print 'Current Letter :', letter
  
var = 10                    # Second Example
while var > 0:              
   print 'Current variable value :', var
   var = var -1
   if var == 5:
      break

print "Good bye!"
a=Hello
b=Python 

a + b will give HelloPython
a*2 will give -HelloHello
a[1] will give e
[1:4] will give ell
H in a will give 1
M not in a will give 1
print r'\n' prints \n and print R'\n' prints \n 

Python If then else

කොටුව තුළ දීඇති පයිතන් ක‍්‍රමලේඛයේ ප‍්‍රතිදානය කුමක් ද?

j=10
y=4
if j<y or j!=4:
    j-=y
    print j
else:
    y*=j
   print y

(1) 4
(2) 6
(3) 10
(4) 14
(5) 40

Python 3.0

j=10
y=4
if ((j<y) or (j!=4)):
    j-=y
    print (j)
else:
    y*=j 
    print (y)


==================

if, elif, and else program branches

mark=float(raw_input("Please enter a mark"))
if mark >= 40:
  print "You passed."
  print "Well done."
else:
  print "You failed."
  print "too bad."
-----------------



age = 17

if age > 18:
   print "Driving licence issued"
else:
   print "Driving licence not permitted"
if (age >= 12) or (age < 18)):
 print "teen"
else :
if  (age < 12) : 
print "kid"
     else:
          print "adult

Comparing data values
None The null object
0 Integer zero 0
0 Floating point zero
"" Empty strings
{} Empty dictionaries
[] Empty lists
() Empty tuples

magic=input("Enter No ? ")

if not (magic == 8 or magic == 9 or magic ==10 ) :
  print '"Time for Tea", said Boss '
else:
  print '"No Tea !" said Boss'



Python Order of operations

r=11; y=2.5; c=4 වශයෙන් r, y, c විචල්‍යවලට අගය පවරා ඇත.

ඒ අනුව, r%3*c+10/y යන පයිතන් ප‍්‍රකාශයේ නිවැරත්‍ථ අගය කුමක් ද?


(1) 6.2 (2) 8.0 (3) 12.0 (4) 24.0 (5) 40.0






 


command name example output
+ Addition 4+5 9
- Subtraction 8-5 3
* Multiplication 4*5 20
/ Division 19/3 6
% Remainder 19%3 5
** Exponent 2**4 16




The order of operations
  1. parentheses ()
  2. exponents **
  3. multiplication *, division \, and remainder %
  4. addition + and subtraction -
 Multiplication (*) and modulo operator (%) have the same precedence, so you evaluate from left to right for this example 

r%3*c+10/y 
((r% 3)*c)+(10/y)
((11% 3)*4)+(10/2.5)

(2*4)+(4)
12

All operators


+       -       *       **      /       //      %
<<      >>      &       |       ^       ~
<       >       <=      >=      ==      !=
 
100 - 25 * 3 % 4 the result is 97 how?
25*3 = 75
75 % 4 = 3 (4*18 = 72; remainder is 3)
100 - 3 = 97



Operator Description Example
+, - Addition, Subtraction 10 -3
*, /, % Multiplication, Division, Modulo 27 % 7
Result: 6
// Truncation Division (also known as floordivision)
The result of the division is truncated to an integer. Works for integers and floating-point numbers as well
27 % 7
Result: 6
+x, -x Unary minus and Unary plus (Algebraic signs) -3
~x Bitwise negation ~3 - 4
Result: -8
** Exponentiation 10 ** 3
Result: 1000
or, and, not Boolean Or, Boolean And, Boolean Not (a or b) and c
in "Element of" 1 in [3, 2, 1]
<, <=, >, >=, !=, == The usual comparison operators 2 <= 3
|, &, ^ Bitwise Or, Bitwise And, Bitwise XOR 6 ^ 3
<<, >> Shift Operatoren 6 << 3

Python Formating Strings

#program to convert Celsius Temperature to Fahrenheit
c=input ('Enter Temperature in Celsius:')
f=c*9/5.0+32
print "Fahrenheit %d" %f


දී ඇති ක‍්‍රමලේඛය දෝෂ සහිත ය. අපේක්ෂිත ප‍්‍රතිදානය ලබා ගැනීම සඳහා එය නිවැරදි විය යුත්තේ පහත සඳහන් කුමන ආකාරයට ද ?

1. #program to convert Celsius Temperature to Fahrenheit යන පේළිය ඉවත් කිරීම
2. c= input('Enter Temperature in Celsius:') පේළිය c-input('Enter Temperature in Celsius.') ලෙස වෙනස් කිරීම

3. F=c*9/5.0+32 පේළිය f=c*9.0/5.0+32 ලෙස වෙනස් කිරීම
4. print "Fahrenheit %d" %f පේළිය print "Fahrenheit %f" %f ලෙස වෙනස් කිරීම
5. print "Fahrenheit %d" %f පේළිය print "Fahrenheit %f" ලෙස වෙනස් කිරීම

============Theory================
# is a comment
# the calculation gives a floating point data type

>>> k = "user"
>>> v = "niranjan"
>>> "%s=%s" % (k, v)
'user=niranjan' 


The whole expression evaluates to a string. The first %s is replaced by the value of k; the second %s is replaced by the value of v. All other characters in the string  stay as they are

>>> "Name: %s, age: %d" % ('John', 35)
  'Name: John, age: 35' 

C style string formatting:

"%d:%d:d" % (hours, minutes, seconds)


>>> print "Today's  stock price: %f" % 50.4625  
50.462500
>>> print "Today's stock price: %.2f" % 50.4625
50.46
>>> print "Change since yesterday: %+.2f" % 1.5
+1.50

Quick Guide to Python List Operations

mylist=[]
x=20

mylist.append(x)
# Add an item to the end of the list;

mylist.insert(i, x) 
# insert at i , i should exsit

list.exytend(L) 
# Extend the list by appending all the items in the given list

mylist.insert(len(a), x) is equivalent to a.append(x).

mylist.remove(x)
Remove the first item from the list whose value is x.

mylist.pop([i])
Remove the item at the given position in the list, and return it.

Mylist.pop()
# removes and returns the last item in the list.

mylist.index(x)
# Return the index in the list of the first item whose value is x.

mylist.sort() 
# Sort the items of the list, in place.

mylist.reverse()
# Reverse the elements of the list, in place.


>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print a.count(333), a.count(66.25), a.count('x')
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]

============ADVANCED ==============





Using Lists as Stacks

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index. For example:

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

Using Lists as Queues

It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).

Python File Names - පයිතන ලිපිගොනු නාමය

පහත දැක්වෙන්නේ උෂ්ණත්වය සෙල්සියස්  පරිමාණයේ සිට ෆැරන්හයිට් පරිමාණයට පරිවර්ථනය කිරීම සඳහා සැකසූ ක‍්‍රමලේඛයකි. ඒ ඇසුරින් අංක 1 හා 2 ප‍්‍රශ්නවලට පිළිතුරු සපයන්න.

#program to convert Celsius Temperature to Fahrenheit
c=input ('Enter Temperature in Celsius:')
f=c*9/5.0+32
print "Fahrenheit %d" %f

මෙම පයිතන් ක‍්‍රමලේඛය සුරැකීමට (Save) භාවිතා කළ හැකි වඩාත් උචිත සහිත ලිපිගොනු නාමය වන්නේ පහත දැක්වෙන ඒවා අතුරින් කුමක් ද?

1. Temperature Celsius into Fahrenheit.python
2. Temperature Celsius into Fahrenheit.pyp
3. cel_into_fah.pyc
4. cel_into_fah.py
5. temp_conv.pyc

Hints
Python don't use python and pyp extensions
Temperature is a common word for Celsius, Fahrenheit as well as Kelvin

A module is a file containing Python definitions and statements.
The file name is the module name with the suffix .py appended. 


hello.pyc is a compiled version of hello.py  to speed-up of the start-up time for short programs.
a -“byte-compiled” version of the module spam.

Packages structure Python namespace by using “dotted module names”.
See Below Advanced...

Naming

file_name.py


Inside code
ClassName, method_name, ExceptionName, function_name, GLOBAL_VAR_NAME, instance_var_name, function_parameter_name, local_var_name.


Modules (program.py)
short,
all_lowercase names,
_underscores can be used

Python packages
_underscores is discouraged.


inside
case_senitivity

joined_lower  :  functions, methods, attributes

joined_lower or ALL_CAPS : constants

StudlyCaps :  classes

Attributes: interface, _internal, __private

avoid  __python_internal_form_





====================Advanced ===============
Package Sound

sound/                          Top-level package
      __init__.py               Initialize the sound package
      formats/                  Subpackage for file format conversions
              __init__.py
              wavread.py
              wavwrite.py
              aiffread.py
              aiffwrite.py
              auread.py
              auwrite.py
              ...
      effects/                  Subpackage for sound effects
              __init__.py
              echo.py
              surround.py
              reverse.py
              ...
      filters/                  Subpackage for filters
              __init__.py
              equalizer.py
              vocoder.py
              karaoke.py
              ...


import sound.effects.echo
sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)