csci/cmpe 4341 topic: programming in python review: exam i xiang lian the university of texas –...

30
CSCI/CMPE 4341 Topic: CSCI/CMPE 4341 Topic: Programming in Python Programming in Python Review: Exam I Review: Exam I Xiang Lian The University of Texas – Pan American Edinburg, TX 78539 [email protected]

Upload: jasper-townsend

Post on 14-Jan-2016

214 views

Category:

Documents


1 download

TRANSCRIPT

  • CSCI/CMPE 4341 Topic: Programming in Python Review: Exam IXiang LianThe University of Texas Pan AmericanEdinburg, TX [email protected]

  • ReviewChapters 1 ~ 4 in your textbookLecture slidesIn-class exercises

    *

  • ReviewMultiple ChoiceTrue/False StatementsProgrammingFind bugsWrite the codeBonus Question (20 extra points)*

  • Chapter 1: Introduction to PythonBasic components in a computer systemThe evolution of programming languageStructured programmingObject-oriented programmingCan you list several differences between C++ and Python? *

  • PythonPython is a scripting languageIt is not compiled as an executable filePythonStructured programmingDivide and conquerObject-oriented programmingClass and objectData encapsulationInheritancePolymorphism

    *

  • Chapter 2: Basic Concepts in Python ProgrammingCommonly used Python rules/functions#print()input()int()id()type()Escape charactersArithmetic operators and their precedenceString formatting

    *

  • First Program in Python: Printing a Line of TextPythonThe # symbolUsed to denote a single line commentThe print functionUsed to send a stream of text to be output to the userExecutingSaving as a fileType code into a .py file and save itTo run it type python fileName.pyExecuting codeType python in the command lineRuns the python interpreter

    "//" or "/* */" is used in C/C++/Java"printf" or "cout" is used in C/C++"System.out.println(...)" in Java*

  • Examples of Escape Characters*

    Escape Sequence

    Description

    \n

    Newline. Move the screen cursor to the beginning of the next line.

    \t

    Horizontal tab. Move the screen cursor to the next tab stop.

    \r

    Carriage return. Move the screen cursor to the beginning of the current line; do not advance to the next line.

    \b

    Backspace. Move the screen cursor back one space.

    \a

    Alert. Sound the system bell.

    \\

    Backslash. Print a backslash character.

    \"

    Double quote. Print a double quote character.

    \'

    Single quote. Print a single quote character.

  • Arithmetic Operators Symbols* # multiply/ # divide% # modulus** # exponential// # floor divisionOrderOperators are done in order of parenthesis, exponents, multiply and divide (left to right), and lastly add and subtract (left to right)*

  • Precedence of Arithmetic Operators*

    Operator(s)

    Operation(s)

    Order of Evaluation (Precedence)

    ( )

    Parentheses

    Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses on the same level (i.e., not nested), they are evaluated left to right.

    **

    Exponentiation

    Evaluated second. If there are several, they are evaluated right to left.

    * / // %

    Multiplication

    Division

    Modulus

    Evaluated third. If there are several, they are evaluated left to right. [Note: The // operator is new in version 2.2]

    + -

    Addition

    Subtraction

    Evaluated last. If there are several, they are evaluated left to right.

    Fig. 2.16Precedence of arithmetic operators.

    2002 Prentice Hall. All rights reserved.Outline

    Fig02_19.py# Fig. 2.19: fig02_19.py# String formatting. integerValue = 4237print ("Integer ", integerValue)print ("Decimal integer %d" % integerValue)print ("Hexadecimal integer %x\n" % integerValue) floatValue = 123456.789print ("Float", floatValue)print ("Default float %f" % floatValue )print ("Default exponential %e\n" % floatValue ) print ("Right justify integer (%8d)" % integerValue)print ("Left justify integer (%-8d)\n" % integerValue ) stringValue = "String formatting"print ("Force eight digits in integer %.8d" % integerValue )print ("Five digits after decimal in float %.5f" % floatValue )print ("Fifteen and five characters allowed in string:" )print ("(%.15s) (%.5s)" % ( stringValue, stringValue ) )

  • Chapters 3 & 4: Control Structures The syntax of basic sequence, selection, and repetition structures in PythonSelectionif, if/else, if/elif/elseEmpty statement: passCounter-controlled and sentinel-controlled repetitionwhile, forbreak, continueAugmented assignmentLogical operators

    *

  • Control Structure3 control structuresSequential structureBuilt into PythonSelection structureThe if statementThe if/else statementThe if/elif/else statementRepetition structureThe while repetition structureThe for repetition structure*

  • Syntax of Control Structure*total = total + Gradecounter = counter + 1if Grade>=60: print ("Passed")if Grade>=60: print ("Passed")else: print ("Failed")

  • Syntax of Control Structure (cont'd)*if Grade>=90: print ("A")else: if Grade>=80: print ("B") else: if Grade >=70: print ("C") else: if Grade>=60: print ("D") else: print ("F")if Grade>=90: print ("A")elif Grade>=80: print ("B")elif Grade >=70: print ("C")elif Grade>=60: print ("D")else: print ("F")

  • Syntax of Control Structure (cont'd)*Product = 1while Product < 1000: Product = 2* Productfor Product in range(1, 1000): Product = 2* Product

  • *for Repetition StructureThe for loopFunction range is used to create a list of valuesrange ( integer )Values go from 0 to given integerrange ( integer1, integer2)Values go from first up to second integerrange ( integer1, integer2, integer )Values go from first up to second integer, but increases in intervals of the third integerThe loop will execute as many times as the value passedfor counter in range ( value ):[0, integer-1][integer1, integer2-1][integer1, integer2-1]*

  • break and continue StatementsThe break statementUsed to make a loop stop loopingThe loop is exited and no more loop code is executedThe continue statementUsed to continue the looping processAll following actions in the loop are not executedBut the loop will continue to run*

  • Logical OperatorsOperatorsandEvaluates to true if both expressions are trueorEvaluates to true if at least one expression is truenotReturns true if the expression is falseNot required in any program*

  • and Logical Operator*

    expression1

    expression2

    expression1 and expression2

    False

    False

    False

    False

    True

    False

    True

    False

    False

    True

    True

    True

    Fig. 3.27 Truth table for the and (logical AND) operator.

  • or Logical Operator*

    expression1

    expression2

    expression1 or expression2

    False

    False

    False

    False

    True

    True

    True

    False

    True

    True

    True

    True

    Fig. 3.29Truth table for the or (logical OR) operator.

  • not Logical Operator*

    expression

    not expression

    False

    True

    True

    False

    Fig. 3.30Truth table for operator not (logical negation).

  • Chapter 5: Functions Modules and pre-defined functionsimport moduleNamemathmath.floor ()math.ceil ()math.cos ()math.pow ()randomrandom.randrange()Syntax of user-defined functionsRecursive functionDefault arguments

    *

  • *Module math FunctionsModuleContains function definitions and other elementsAll of which are related in some wayCalling a functionfunctionName ( argument1, argument2 )The import keyword is used to include a moduleInvoking functions from a moduleUse the module name followed by the dot operator (.)moduleName.functionName( argument )

  • *Random-Number GenerationThe random moduleUsed to generate a random number for the programmerFunction randrangeGenerates a number from the first argument up to, but not including, the second argumentEach number in the range has the same likelihood of being selected by the function

  • Examples of Floor and Ceilingfloor function: math.floor(2.10) = 2 math.floor(2.00) = 2 math.floor(1.90) = 1 math.floor(1.80) = 1 ceil function: math.ceil(0.00) = 0 math.ceil(0.10) = 1 math.ceil(0.20) = 1 math.ceil(0.30) = 1 *

  • *User-Defined FunctionsDefinitionsFunctions must be defined before they are useddef functionName ( paramList ):functionName is a valid identifierparamList is a comma separated list of parameters receivedThe actions of the functions then followsThey should all be indented appropriatelyThe actions are also called the block or the function body

  • RecursionMethod that calls itselfA recursive method solves only a simple problem (base case)For any thing other than the base case, it calls itself with a slightly simpler problemEventually it becomes the base case for which it knows the answer*

  • *Default ArgumentsFunction argumentsFunctions may commonly receive a particular value typeWhen this is true a default argument can be setMust appear to the right of any other argumentsA default value can also be setIf passes a value then the default value is overridden

  • Good Luck!Q/A

    *****