Python Programming - III. Controlling the Flow

2,394 views

Published on

Feel free to download the material for offline viewing later, better images' resolutions, and crispier fonts.

Published in: Technology, Education
  • Be the first to comment

Python Programming - III. Controlling the Flow

  1. 1. PYTHON PROGRAMMING III. Controlling the Flow Engr. Ranel O. Padon
  2. 2. PYTHON PROGRAMMING TOPICS I •  Introduction to Python Programming II •  Python Basics III •  Controlling the Program Flow IV •  Program Components: Functions, Classes, Modules, and Packages V •  Sequences (List and Tuples), and Dictionaries VI •  Object-Based Programming: Classes and Objects VII •  Customizing Classes and Operator Overloading VIII •  Object-Oriented Programming: Inheritance and Polymorphism IX •  Randomization Algorithms X •  Exception Handling and Assertions XI •  String Manipulation and Regular Expressions XII •  File Handling and Processing XIII •  GUI Programming Using Tkinter
  3. 3. CONTROLLING THE FLOW
  4. 4. CONTROLLING THE FLOW
  5. 5. CONTROLLING THE FLOW
  6. 6. CONTROLLING THE FLOW: STRUCTURES
  7. 7. DECISION-MAKING our lives are filled with choices:
 
 1. Saan ako kakain? 2. Gi-gimmick ba ako sa Friday? 3. Gusto niya rin kaya ako?
 
 
 
 
 

  8. 8. DECISION-MAKING many choices you make depend on other circumstances
 1. Saan ako kakain?
 May budget pa ba akong malupit? (Yes|No)
 2. Gi-gimmick ba ako sa Friday?
 Wala ba ako kelangang tapusin? (Yes|No)
 3. Gusto niya rin kaya ako? Lagi ba syang nagpaparamdam sa akin? (Yes|No)
 
 
 
 

  9. 9. ALGORITHMS Before writing a program to solve a particular problem, it is essential to have a thorough understanding of the problem and a carefully planned approach to solving the problem. The Elevator-Mirror Problem
  10. 10. ALGORITHMS Any computing problem can be solved by executing a series of actions in a specified order.
 
 An algorithm is a procedure for solving a problem in terms of
 1. actions to be executed 2. the order of execution
  11. 11. ALGORITHMS “rise-and-shine” algorithm for getting out of bed and going to work: 
 (1) get out of bed (2) take off pajamas (3) take a shower, (4) get dressed (5) eat breakfast (6) carpool to work.
  12. 12. ALGORITHMS Suppose that the same steps are performed in a slightly different order: (1) get out of bed (2) take off pajamas (3) get dressed (4) take a shower (5) eat breakfast (6) carpool to work
  13. 13. PSEUDOCODE Pseudocode is an artificial and informal language that helps programmers develop algorithms.
 
 Characteristics q similar to everyday English q convenient and user-friendly q not an actual computer programming language
  14. 14. PSEUDOCODE Pseudocode helps the programmer “plan” a program before attempting to write it in a programming language
 
 A carefully prepared pseudocode program can be converted easily to a corresponding Python program
  15. 15. PROGRAM CONTROL Program Control
 specifying the order in which statements are to be executed in a computer program
  16. 16. CONTROL STRUCTURES By default, program execution is sequential.
 
 You could break this behavior using transfer of control.
 
 Transfer of Control makes use of Control Structures.
  17. 17. STRUCTURED PROGRAMMING In the 1960’s, indiscriminate use of transfer of controls, especially goto statements, resulted to spaghetti code.
 
 Structured programming is synonymous to goto elimination or goto-less programming.
  18. 18. STRUCTURED PROGRAMMING Structured programs are clearer, easier to debug and modify and more likely to be bug-free in the first place.
  19. 19. CONTROL STRUCTURES Structured programs could be written in terms of three control structures:
 
 I. Sequence 
 II. Selection III. Repetition
  20. 20. CONTROL STRUCTURES I. Sequence Control Structure
 
 - the default flow of program 

  21. 21. CONTROL STRUCTURES II. Selection Control Structures
 
 a. if (single selection) b. if/else (double selection) c. if/elif/else (multiple selection) 

  22. 22. CONTROL STRUCTURES III. Repetition Control Structures
 
 a. while (single selection) b. for (double selection) 

  23. 23. CONTROL STRUCTURES In Summary:
 
 I. Sequence 
 II. Selection (if, if/else, if/elif/else) III. Repetition (while, for)
  24. 24. CONTROL STRUCTURES Any Python program can be constructed from 6 different types of control structures (sequence, if, if/else, if/elif/else, while and for) combined in 2 ways (control-structure stacking and control-structure nesting)
  25. 25. CONDITIONAL STATEMENT A conditional statement is basically a simple yes or no question.
 ‘Mahal mo ba ako?’: ‘Oo’: “Pakasal na tayo.” ‘Hindi Eh’: “Iyak na lang ako.” 
 
 
 
 
 

  26. 26. CONDITIONAL STATEMENTS Conditional statements are one of the most important programming concepts: They let your programs react to different situations and behave intelligently.
  27. 27. CONDITIONAL STATEMENTS
  28. 28. CONDITIONAL STATEMENTS Conditional statements are also called “if/then” statements, because they perform a task only if the answer to a question is true: ‘If may sapat akong pera, then bibili ako ng Windows 8!’
  29. 29. if SELECTION STRUCTURE if (kondisyon): # mga gagawin kung totoo ung kondisyon
 
 if (maitim == True): print “maitim ako!” Note: Parentheses are optional.
  30. 30. if SELECTION STRUCTURE Pseudocode: Code:
  31. 31. if SELECTION STRUCTURE Flowchart:
  32. 32. if/else SELECTION STRUCTURE
  33. 33. if/elif/else SELECTION STRUCTURE
  34. 34. if/elif/else SELECTION STRUCTURE
  35. 35. if/elif/else SELECTION STRUCTURE
  36. 36. if/elif/else SELECTION STRUCTURE A nested if/else structure is faster than a series of single-selection if structures because the testing of conditions terminates after one of the conditions is satisfied.
  37. 37. if/elif/else SELECTION STRUCTURE In a nested if/else structure, place the conditions that are more likely to be true at the beginning of the nested if/else structure. This enables the nested if/else structure to run faster and exit earlier
  38. 38. COMPOUND STATEMENT
  39. 39. EMPTY STATEMENT if gender == “sirena”: pass
  40. 40. while REPETITION STRUCTURE
  41. 41. COUNTER-CONTROLED REPETITION
  42. 42. COUNTER-CONTROLED REPETITION
  43. 43. COUNTER-CONTROLED REPETITION
  44. 44. COUNTER-CONTROLED REPETITION Because floating-point values may be approximate, controlling the counting of loops with floating-point variables may result in imprecise counter values and inaccurate tests for termination. Programs should control counting loops with integer values.
  45. 45. SENTINEL-CONTROLED REPETITION Sentinel Value: also called as dummy value, signal value or flag value
  46. 46. SENTINEL-CONTROLED REPETITION
  47. 47. SENTINEL-CONTROLED REPETITION
  48. 48. SENTINEL-CONTROLED REPETITION
  49. 49. SENTINEL-CONTROLED REPETITION In a sentinel-controlled loop, the prompts requesting data entry should explicitly remind the user of the sentinel value.
  50. 50. NESTED CONTROL STRUCTURES Write a program to summarize the exam results of 10 students. Next to each name is written a I if the student passed the exam and a 2 if the student failed.
 
 1. Input each test result (i.e., a 1 or a 2). Display the message “Enter result” on the screen each time the program requests another test result. 2. Count the number of test results of each type. 3. Display a summary of the test results: the number of students who passed and the number of students who failed. 4. If more than 8 students passed the exam, print the message “Raise tuition.”
  51. 51. NESTED CONTROL STRUCTURES
  52. 52. NESTED CONTROL STRUCTURES
  53. 53. NESTED CONTROL STRUCTURES Sample Run 1:
  54. 54. NESTED CONTROL STRUCTURES Sample Run 2:
  55. 55. NESTED CONTROL STRUCTURES The most difficult part of solving a problem on a computer is developing an algorithm for the solution. Once a correct algorithm has been specified, the process of producing a working Python program from the algorithm normally is straightforward.
  56. 56. for REPETITION STRUCTURE
  57. 57. for REPETITION STRUCTURE the built-in range(start, end, step) function returns a list containing integers in the range of start to end-1.
 
 What is range(10, 0, -1)?
  58. 58. for REPETITION STRUCTURE
  59. 59. for REPETITION STRUCTURE PRACTICE EXERCISE:
 
 using for loop print the following number series: a.) 7, 14, 21, …, 70, 77 b.) 20, 18, 16, …, 4, 2 c.) 99, 88, 77, …, 11, 0
  60. 60. for REPETITION STRUCTURE
  61. 61. for REPETITION STRUCTURE Compound Interest
  62. 62. for REPETITION STRUCTURE
  63. 63. while VERSUS for REPETITION
  64. 64. STRUCTURED PROGRAMMING SUMMARY
  65. 65. break AND continue STATEMENTS programmer could also alter the flow of a loop using the break and continue statements
  66. 66. break STATEMENT breaks or causes immediate exit from while or for structure
  67. 67. break STATEMENT
  68. 68. break STATEMENT
  69. 69. continue STATEMENT skips the remaining statements in the body of a while or for structure and proceeds with the next iteration of the loop
  70. 70. continue STATEMENT causes immediate exit from while or for structure
  71. 71. break AND continue STATEMENTS break and continue statements are also used to improve performance by minimizing the amount of processing by causing early exit or avoiding unneeded computations or cases.
  72. 72. LOGICAL OPERATORS Relational Operators: <, >, <=, >=, ==, != Logical Operators: and, or, not
  73. 73. LOGICAL and OPERATOR
  74. 74. LOGICAL or OPERATOR
  75. 75. LOGICAL not OPERATOR
  76. 76. AUGMENTED ASSIGNMENT Assignment Expressions could be abbreviated.
  77. 77. AUGMENTED ASSIGNMENT The += symbol adds the value of the expression on the right of the += sign to the value of the variable on the left of the sign and stores the result in the variable on the left of the sign.
  78. 78. AUGMENTED ASSIGNMENT
  79. 79. AUGMENTED ASSIGNMENT
  80. 80. PYTHON 2.2 KEYWORDS special/reserved words used for control structures & other Python features they could not be used as variable names
  81. 81. PRACTICE EXERCISE 1 Write a program that reads a positive integer and determines if it is a prime number or not.

  82. 82. PRACTICE EXERCISE 2 A palindrome is a number or a text phrase that reads the same backwards or forwards. For example, each of the following five-digit integers is a palindrome: 12321, 55555, 45554 and 11611. Write a program that reads in a five-digit integer and determines whether it is a palindrome. (Hint: Use the division and modulus operators to separate the number into its individual digits.)
  83. 83. PRACTICE EXERCISE 3 Write a program that reads a nonnegative integer and computes and prints its factorial.
 
 The factorial of a nonnegative integer n is written n! n! = n· (n - 1) · (n - 2) · … · 1 (for values of n >= 1) and n! = 1 (for n = 0). For example, 5! = 5 · 4 · 3 · 2 · 1, which is 120.
  84. 84. PRACTICE EXERCISE 4 What is the output of this? Explain why.
 for row in range(0,5): print “*”
  85. 85. PRACTICE EXERCISE 5 What is the output of this? Explain why.
 for row in range(0,5): for column in range(0,3): print “*” print
  86. 86. PRACTICE EXERCISE 6 What is the output of this? Explain why.
 for row in range(0,5): for column in range(0,3): print “*”, print
  87. 87. PRACTICE EXERCISE 7 What is the output of this? Explain why.
 for group in range(0,3): for row in range(0,4): for column in range(0,5): print "*", print print
  88. 88. To be able to control the flow is powerful!
  89. 89. REFERENCES q  Deitel, Deitel, Liperi, and Wiedermann - Python: How to Program (2001). q  Disclaimer: Most of the images/information used here have no proper source citation, and I do not claim ownership of these either. I don’t want to reinvent the wheel, and I just want to reuse and reintegrate materials that I think are useful or cool, then present them in another light, form, or perspective. Moreover, the images/information here are mainly used for illustration/educational purposes only, in the spirit of openness of data, spreading light, and empowering people with knowledge. J

×