Python2[1]

83
Mr Nuwan Kodagoda Head/Department of Information Technology Sri Lanka Institute of Information Technology GCE (A/L) ICT Training for Teachers (Last Updated on 21st March 2011)

description

Python2[1]

Transcript of Python2[1]

  • Mr Nuwan KodagodaHead/Department of Information TechnologySri Lanka Institute of Information Technology

    GCE (A/L) ICT Training for Teachers (Last Updated on 21st March 2011)

  • OutcomesIntroduction to PythonData Types and CalculationsSelectionRepetitionString HandlingFunctionsListsFile HandlingClasses

    GCE (A/L) ICT Training for Teachers

  • Programming Languages

  • Programming LanguagesThere are hundreds of programming languages.Very broadly these languages are categorized as Low Level LanguagesHigh Level Languages

  • Low Level LanguagesMore closer to the Architecture of the computer.Very difficult for us humans to use.

    Memory AddressesMachine CodeAssembly

  • High Level LanguagesHigh Level Languages are closer to human languages.

    Dim radius as integerDim area as integer

    radius = txtRadius.textarea = 22/7*radius*radiusmsgbox area

  • How a Computer Program worksThe Program you write is executed by the CPU.

    Since the CPU can only understand machine code your program needs to be converted into machine code.

  • How a Computer Program worksDim radius as integerDim area as integer

    radius = txtRadius.textarea = 22/7*radius*radiusmsgbox areaC8B723A7D7AA89DD89D23A9F4A9...Source CodeMachine Code

  • How a Computer Program worksThe software that does the conversion to machine code comes in two flavours.

    CompilersInterpreters

  • What is a Compiler?A compiler converts your entire program to machine code at one go.

    After compilation you have an executable file.

    e.g. an EXE, COM file for PCs

  • How an Interpreter WorksAn Interpreter converts your program to machine code one instruction at a time.

  • PythonPython is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python is an ideal language for scripting and rapid application development in many areas on most platforms.GCE (A/L) ICT Training for Teachers

  • Python LanguageNo variable, data type declaration necessary (Dynamically Typed)Case Sensitive variablesIndentation of 4 characters used for block structures (e.g. if, while, functions)Program extension is .pyRuns on multiple platformsOpen SourceGCE (A/L) ICT Training for Teachers

  • Python KeywordsLike most modern languages Python has only a few keywords.GCE (A/L) ICT Training for Teachers

  • HistoryDeveloped in the early 1990s by Guido van Rossum.The name Python was based a popular TV show called the Monty Python.

    GCE (A/L) ICT Training for Teachers

  • Which version of Python should I use?There are two versions of Python availablePython 2 the latest is 2.71Python 3 the latest is 3.2For the ICT exam use Python 2Some differences e.g. in Python 3 the print is a function so print 10, 20 has to be written as print(10,20)GCE (A/L) ICT Training for Teachers

  • Downloading Python and InstallingGCE (A/L) ICT Training for Teachers

  • Operator PrecedenceGCE (A/L) ICT Training for Teachers

    OperatorDescriptionAssociatively* / %Multiplication/division/modulusleft-to-right+ -Addition/subtractionleft-to-right

  • Arithmetic OperatorsGCE (A/L) ICT Training for Teachers

    (Python 3 only)

  • MCQ Question 41r=11; y=2.5; c=4 have been assigned to three variablesFind the value of r%3*c+10/y

    GCE (A/L) ICT Training for Teachers

  • MCQ Question 41r=11; y=2.5; c=4 have been assigned to three variablesFind the value of r%3*c+10/y11%3*4+10/2.52*4+10/2.58+10/2.58+4.012.0

    GCE (A/L) ICT Training for Teachers

  • Numerical Calculations10+20/2(10+20)/2

    GCE (A/L) ICT Training for Teachers

  • Printing values in Pythonprint 10, Nadun, 1990

    In Python 3 print is a function

    print(10, Nadun, 1990)GCE (A/L) ICT Training for Teachers

  • Input Data in Python 2no1 = int(input(Enter an int Number : ))no2 = float(input(Enter a float Number : ))str = raw_input(Enter a string : )

    GCE (A/L) ICT Training for Teachers

  • CalculationsWrite a python program to input a length in mm and convert it to inches.25.4 mm = 1 inchGCE (A/L) ICT Training for Teachers

    inches.py

  • CalculationsWrite a python program to input a temperature in Celcius and convert it to Fahrenheit.

    fahrenheit = 9/5* celcius +32GCE (A/L) ICT Training for Teachers

    celcius.py

  • SelectionGCE (A/L) ICT Training for Teachers

    if (cond) then Statement A else Statement B endif

  • SelectionGCE (A/L) ICT Training for Teachers

    if (cond) then Statement A else Statement B endifif cond: Statement A else: Statement B

  • if statementWrite a program to input a mark and display Pass if it is greater than or equal to 50. Otherwise display Fail.GCE (A/L) ICT Training for Teachers

  • if statementWrite a program to input a number. Display if it is an even or an odd number.GCE (A/L) ICT Training for Teachers

    oddeven.py

  • Nested if statementGCE (A/L) ICT Training for Teachers

    if (test1) then block1else if (test2) then block2 else elseBlock endifendif

  • Nested if statementGCE (A/L) ICT Training for Teachers

    if (test1) then block1else if (test2) then block2 else elseBlock endifendif if test1: block1elif test2: block2else: elseBlock

  • Nested If StatementGCE (A/L) ICT Training for Teachers

  • GradesWrite a program to input the marks of a student and calculate the grades.> 75 A65 to 75 B55 to 64 C45 to 54 S< 45 - W

    GCE (A/L) ICT Training for Teachers

  • Nested If StatementWrite a program to input an amount and to calculate the discount as follows.Discounts>1000 - discount 10%500-1000 - discount 5%< 500 - discount 2%GCE (A/L) ICT Training for Teachers

  • MCQ Question 42What would be the output of this program.GCE (A/L) ICT Training for Teachers

  • MCQ Question 42If 10
  • Repetitiondo while (cond) execute Statement end whileGCE (A/L) ICT Training for Teachers

  • Repetitiondo while (cond) execute Statement end whileGCE (A/L) ICT Training for Teachers

    while cond: execute Statement

  • whileWrite a program to Print numbers 1 to 9

    GCE (A/L) ICT Training for Teachers

    while1.py

  • whileWrite a program to Print numbers 1,3,5,7,9

    GCE (A/L) ICT Training for Teachers

    while2.py

  • whileWrite a program to print the tables of 7.GCE (A/L) ICT Training for Teachers

  • Using For loop in PythonRange command generates a list.A list is similar to an array, but it can store data of different types. It also could contain another list.range(1,10) produces the list[1,2,3,4,5,6,7,8,9]

    GCE (A/L) ICT Training for Teachers

    for r in range(1,10): print(r)

  • Using For loop in Pythonrange(1,10,2) produces the list[1,3,5,7,9]

    GCE (A/L) ICT Training for Teachers

    for r in range(1,10,2): print(r)

  • Using For loop in PythonAny list can be printed in the same wayMylist = [Java,C#, VB6, VB.NET,Python]

    GCE (A/L) ICT Training for Teachers

    for r in Mylist: print(r)JavaC#VB6VB.NETPython

  • Using For loop in PythonThis works the same for a stringcountry = SRI LANKA

    GCE (A/L) ICT Training for Teachers

    for r in country: print(r)SRI

    LANKA

  • MCQ Question 43 What would be the output ?GCE (A/L) ICT Training for Teachers

  • MCQ Question 43 What would be the output ?r= 5s=3r = r+sr = 5+3 = 8s = r+3=8+3print 11r
  • MCQ Question 43 What would be the output ?r=8s=11r = r+sr = 8+11 = 19s = r+3=19+3=22print 22r
  • MCQ Question 43 What would be the output ?r=19s=22r = r+sr = 19+22 = 41s = r+3=41+3=44print 44r
  • MCQ Question 44 GCE (A/L) ICT Training for Teachers

    Select the correct pseudo code for the given flow chart

  • MCQ Question 45Which of the above statements are correctGCE (A/L) ICT Training for Teachers

  • String Manipulationmystr = Sri Lankalen(mystr)mystr.upper() # upper casemystr.upper() # lower casemystr[0] # Smystr[-1] # a

    GCE (A/L) ICT Training for Teachers

  • List Manipulationmylist = [10, Ajith, 67.3, 78.2]mylist[0] # 10mylist[3] # 78.2mylist[-1] # 78.2mylist[-2] # 67.3sublist = mylist[1:3] # [Ajith, 67.3]sublist = mylist[1:] # [Ajith, 67.3, 78.2]

    GCE (A/L) ICT Training for Teachers

  • List Manipulationlen(mylist) #4mylist.append(89) # adds 89# [10, Ajith, 67.3, 78.2, 89]mylist.sort() # sorts listmylist.reverse() # reverses listGCE (A/L) ICT Training for Teachers

  • Break and ContinueA break statement inside a block will cause it to exit the loopA continue statement inside a block will skip the remaining instructions and go to the beginning of the loop.GCE (A/L) ICT Training for Teachers

  • Question II 3GCE (A/L) ICT Training for Teachers

    python

    AQ3c.py

  • Question II 3GCE (A/L) ICT Training for Teachers

    pythonprogramming (one letter per line)

    AQ3d.py

  • Part B Question 51 Cat 32 Dog 33 Rat 3GCE (A/L) ICT Training for Teachers

    BQ5b.py

  • FunctionsA function that returns a value or does a particular task

    def cube(x): return x*x*x

    cube(10)GCE (A/L) ICT Training for Teachers

  • FunctionsWrite a function that converts mm to inches

    GCE (A/L) ICT Training for Teachers

  • ExampleWrite a python program that returns the maximum of two numbersmax(10,30) # should return 30GCE (A/L) ICT Training for Teachers

  • Importing modules and functionsAssume there is a program called pythonprg.py which has two functions named func1() and func2()To use these functions from another python program we need to do the following.

    GCE (A/L) ICT Training for Teachers

    import pythonprgpythonprg.func1(3)

    from pythonprg import func1,func2func1(3)

  • Setting PYTHONPATHStartCMDSET PYTHONPATH= c:\python27;c:\python27\programs

    Importing modules from IDLEimport syssys.path.append(c:\\python27\\programs)

    GCE (A/L) ICT Training for Teachers

  • Part B Question 55 x 1 = 55 x 2 = 105 x 3 = 155 x 4 = 205 x 5 = 255 x 6 = 305 x 7 = 355 x 8 = 405 x 9 = 455 x 10 = 505 x 11 = 55GCE (A/L) ICT Training for Teachers

    BQ5b2.py

  • Question II 3GCE (A/L) ICT Training for Teachers

  • Pseudo Code for above flow chart# Pseudo code# x = 1# total = 0# do while (x 50) then# display "Good"# else# display "Bad"# endifGCE (A/L) ICT Training for Teachers

  • Python Codex = 1total = 0while x 50: print "Good"else: print "Bad"GCE (A/L) ICT Training for Teachers

  • File HandlingPython allows you to easily read and write data filesGCE (A/L) ICT Training for Teachers

  • Write data to a fileWrite a sample program to store data to a data file where commas separate values.

    datafile = open ("marks.dat","w")datafile.write()GCE (A/L) ICT Training for Teachers

  • Read data from a fileWrite a sample program to read data from a data file where commas separate values.datafile = open ("marks.dat","r")record = datafile.readline()# split the data into a list for easier manipulation. The comma is the seperatormylist = record.strip(\n).split(,)GCE (A/L) ICT Training for Teachers

  • Part B Question 5GCE (A/L) ICT Training for Teachers

    BQ5c.py

  • Object Oriented ProgramPython Supports OO just like any other modern programming languagePython code as usual is minimilisticBoth methods and attributes can be accessed from outside.GCE (A/L) ICT Training for Teachers

  • Classes and ObjectsA person workingIn a companyPerson

    EmpNoNameAddressBasicSalOtHrsOtRate

    CalcOtAmtCalcNetSalPropertiesMethods

  • Classes and ObjectsYou describe the objects details in a Class. A class is a blue print of an object.

    Blue PrintHouse3House2House1

  • Classes# Shape.pyclass Rectangle: def __init__(self,x,y): def display(self): GCE (A/L) ICT Training for Teachers

    import Shaperec1 = Shape.Rectangle(10,20)rec1.display()

  • Classes# Shape.pyclass Rectangle: def __init__(self,x,y): def display(self): GCE (A/L) ICT Training for Teachers

    from Shape import Rectanglerec1 = Rectangle(10,20)rec1.display()

  • CircleWrite a class to represent a circleCalculate the area pi*r^2Calculate the perimeter 2*pi*rGCE (A/L) ICT Training for Teachers

  • MCQ 50GCE (A/L) ICT Training for Teachers

  • MCQ 50GCE (A/L) ICT Training for Teachers

  • MCQ 49GCE (A/L) ICT Training for Teachers

  • ExercisesWrite a program to input a series of numbers terminated by -999. Calculate and print the sum of the numbers entered.GCE (A/L) ICT Training for Teachers

  • ExerciseWrite a program to input the sum of 10 numbers.Modify the above program using a break statement so that when the number -999 is entered it will stop the entering of marksModify the above program to ignore negative numbers (except for -999). Use the continue statementGCE (A/L) ICT Training for Teachers