Chapter 2 Writing Simple Programs Python Programming: An Introduction to Computer Science JPM02 22/02/2023 Fundamentos de Programação 1
Objectives To know the steps in an orderly software development process. To understand programs following the input, process, output (IPO) pattern and be able to modify them in simple ways. To understand the rules for forming valid Python identifiers and expressions. 22/02/2023 Fundamentos de Programação 2
Objectives To be able to understand and write Python statements to output information to the screen, assign values to variables, get numeric information entered from the keyboard, perform a counted loop 22/02/2023 Fundamentos de Programação 3
The Software Development Process 22/02/2023 Fundamentos de Programação 4
22/02/2023 Fundamentos de Programação 5
The Software Development Process The process of creating a program is often broken down into stages according to the information that is produced in each phase. 22/02/2023 Fundamentos de Programação 6
The Software Development Process Analyze the Problem
Figure out exactly the problem to be solved. Try to understand it as much as possible. 22/02/2023 Fundamentos de Programação 7
22/02/2023 Fundamentos de Programação 8
The Software Development Process Determine Specifications
Describe exactly what your program will do. Don’t worry about how the program will work, but what it will do. Includes describing the inputs, outputs, and how they relate to one another. 22/02/2023 Fundamentos de Programação 9
The Software Development Process Create a Design Formulate the overall structure of the program. This is where the how of the program gets worked out. Develop your own algorithm that meets the specifications. 22/02/2023 Fundamentos de Programação 10
The Software Development Process Implement the Design Translate the design into a computer language. In this course we will use Python. 22/02/2023 Fundamentos de Programação 11
The Software Development Process Test/Debug the Program Try out your program to see if it worked. If there are any errors ( bugs ), they need to be located and fixed. This process is called debugging . Your goal is to find errors, so try everything that might “break” your program! 22/02/2023 Fundamentos de Programação 12
22/02/2023 Fundamentos de Programação 13
:Grace Hopper’s Bug. US Navy/Public Domain. It was really a bug! https://www.edn.com/1st-actual-computer-bug-found-september-9-1947/ https://www.atlasobscura.com/places/grace-hoppers-bug 22/02/2023 Fundamentos de Programação 14
The Software Development Process Maintain the Program Continue developing the program in response to the needs of users . Programs are never completely finished – they evolve over time, due to Computer change Language change Spec change 22/02/2023 Fundamentos de Programação 15
Program Example 22/02/2023 Fundamentos de Programação 16
Example Program: Temperature Converter Analysis – the temperature is given in Celsius, user wants it expressed in degrees Fahrenheit. Specification Input – temperature in Celsius Output – temperature in Fahrenheit Output = 9/5(input) + 32 22/02/2023 Fundamentos de Programação 17
Temperature conversion 22/02/2023 Fundamentos de Programação 18
Example Program: Temperature Converter Design Input, Process, Output (IPO) Prompt the user for input (Celsius temperature) Process it to convert it to Fahrenheit using F = 9/5(C) + 32 Output the result by displaying it on the screen 22/02/2023 Fundamentos de Programação 19
Example Program: Temperature Converter Before we start coding, let’s write a rough draft of the program (pseudocode) Pseudocode is precise common language English/Portuguese that describes what a program does, step by step. Using pseudocode, we can concentrate on the algorithm rather than the programming language. 22/02/2023 Fundamentos de Programação 20
Example Program: Temperature Converter Pseudocode: Input the temperature in degrees Celsius (call it celsius ) Calculate fahrenheit as (9/5)*celsius+32 Output fahrenheit Now convert this to Python! 22/02/2023 Fundamentos de Programação 21
Example Program: Temperature Converter #convert.py # A program to convert Celsius temps to Fahrenheit # by: Susan Computewell # Ver 12 Set 21 19:04 def main(): celsius = eval (input("What is the Celsius temperature? ")) fahrenheit = (9/5) * celsius + 32 print("The temperature is ", fahrenheit ," degrees Fahrenheit.") main() Cabeçalho : Por sempre 22/02/2023 Fundamentos de Programação 22
Example Program: Temperature Converter Once we write a program, we should test it! >>> What is the Celsius temperature? 0 The temperature is 32.0 degrees Fahrenheit. >>> main() What is the Celsius temperature? 100 The temperature is 212.0 degrees Fahrenheit. >>> main() What is the Celsius temperature? -40 The temperature is -40.0 degrees Fahrenheit. >>> 22/02/2023 Fundamentos de Programação 23
Example Program: Temperature Converter Think output in order to be easy to read . . . >>> Celsius > ------- Fahrenheit -> 32.0 F. 22/02/2023 Fundamentos de Programação 24
Python Programming, 3/e 25 Elements of Programs Names Names are given to variables ( celsius , fahrenheit ), modules (main, convert), etc. These names are called identifiers Every identifier must begin with a letter or underscore (“_”), followed by any sequence of letters, digits, or underscores. Identifiers are case sensitive. 22/02/2023 Fundamentos de Programação 25
Elements of Programs These are all different, valid names X Celsius Spam spam spAm Spam_and_Eggs Spam_And_Eggs 22/02/2023 Fundamentos de Programação 26
Elements of Programs Some identifiers are part of Python itself. These identifiers are known as reserved words (or keywords ). This means they are not available for you to use as a name for a variable, etc. in your program. and, del, for, is, raise, assert, elif , in, print, etc. For a complete list, see Zelle Table 2.1 (p. 32) 22/02/2023 Fundamentos de Programação 27
Elements of Programs Expressions The fragments of code that produce or calculate new data values are called expressions . Literals are used to represent a specific value, e.g. 3.9, 1, 1.0 Simple identifiers can also be expressions. Also included are strings (textual data) and string literals (like "Hello"). 22/02/2023 Fundamentos de Programação 28
Elements of Programs >>> x = 5 >>> x 5 >>> print(x) 5 >>> print(spam) Traceback (most recent call last): File "<pyshell#15>", line 1, in - toplevel - print spam NameError : name 'spam' is not defined >>> NameError is the error when you try to use a variable without a value assigned to it. 22/02/2023 Fundamentos de Programação 29
Python Programming, 3/e 30 Elements of Programs Simpler expressions can be combined using operators . +, -, *, /, ** Spaces are irrelevant within an expression. The normal mathematical precedence applies. ((x1 – x2) / 2*n) + (spam / k**3) 22/02/2023 Fundamentos de Programação 30
Elements of Programs Output Statements print() print(<expr>, <expr>, …, <expr>) A print statement can print any number of expressions. Successive print statements will display on separate lines. A bare print will print a blank line. 22/02/2023 Fundamentos de Programação 31
Elements of Programs print(3+4) print(3, 4, 3+4) print() print(3, 4, end=" "), print(3 + 4) print("The answer is", 3+4) 7 3 4 7 3 4 7 The answer is 7 22/02/2023 Fundamentos de Programação 32
Assignment Statements Simple Assignment <variable> = <expr > variable is an identifier, expr is an expression The expression on the RHS is evaluated to produce a value which is then associated with the variable named on the LHS. 22/02/2023 Fundamentos de Programação 33
Python Programming, 3/e 34 Assignment Statements Variables have meaningfull names Unless you want to keeep code confusing to everyone x = 3.9 * x * (1-x) fahrenheit = 9/5 * celsius + 32 x = 5 22/02/2023 Fundamentos de Programação 34
Assignment Statements Variables can be reassigned as many times as you want! >>> myVar = 0 >>> myVar >>> myVar = 7 >>> myVar 7 >>> myVar = myVar + 1 >>> myVar 8 >>> 22/02/2023 Fundamentos de Programação 35
Assignment Statements Variables are like a box we can put values in. When a variable changes, the old value is erased and a new one is written in . 22/02/2023 Fundamentos de Programação 36
Assignment Statements Technically, this model of assignment is simplistic for Python. Python doesn't overwrite these memory locations (boxes). Assigning a variable is more like putting a “sticky note” on a value and saying, “this is x ”. 22/02/2023 Fundamentos de Programação 37
Assigning Input The purpose of an input statement is to get input from the user and store it into a variable. <variable> = eval (input(<prompt>)) Here, eval is wrapped around the input function. 22/02/2023 Fundamentos de Programação 38
Assigning Input First the prompt is printed The input part waits for the user to enter a value and press <enter> The expression that was entered is evaluated to turn it from a string of characters into a Python value (a number). The value is assigned to the variable. For string input : < var > = input(<prompt>) 22/02/2023 Fundamentos de Programação 39
Assigning Input Beware: the eval function is very powerful and potentially dangerous! When we evaluate user input, we allow the user to enter a portion of our program, which Python will then evaluate. 22/02/2023 Fundamentos de Programação 40
Assigning Input Someone who knows Python could exploit this ability and enter malicious instructions, e.g. capture private information or delete files on the computer . This is called a code injection attack, because an attacker is injecting malicious code into the running program. 22/02/2023 Fundamentos de Programação 41
Assigning Input When writing programs for your own personal use, this is probably not much of an issue. When the input is coming from untrusted sources, like users on the Internet, the use of eval could be disastrous. We will see some safer alternatives in the next chapter. 22/02/2023 Fundamentos de Programação 42
Simultaneous Assignment Several values can be calculated at the same time < var >, < var >, … = <expr>, <expr>, … Evaluate the expressions in the RHS and assign them to the variables on the LHS sum, diff = x+y , x-y 22/02/2023 Fundamentos de Programação 43
Simultaneous Assignment How could you use this to swap the values for x and y? Why doesn’t this work ? x = y y = x We could (must) use a temporary variable… 22/02/2023 Fundamentos de Programação 44
Simultaneous Assignment We can swap the values of two variables quite easily in Python! x, y = y, x >>> x = 3 >>> y = 4 >>> print(x, y) 3 4 >>> x, y = y, x >>> print(x, y) 4 3 22/02/2023 Fundamentos de Programação 45
Simultaneous Assignment We can use this same idea to input multiple variables from a single input statement! Use commas to separate the inputs def spamneggs (): spam, eggs = eval (input("Enter # of slices of spam followed by # of eggs: ")) print ("You ordered", eggs, "eggs and", spam, "slices of spam. Yum!“) >>> spamneggs () Enter the # of slices of spam followed by the # of eggs: 3, 2 You ordered 2 eggs and 3 slices of spam. Yum! >>> 22/02/2023 Fundamentos de Programação 46
Definite Loops A definite loop executes a definite number of times, i.e., at the time Python starts the loop it knows exactly how many iterations to do. for < var > in <sequence>: <body> The beginning and end of the body are indicated by indentation. 22/02/2023 Fundamentos de Programação 47
Definite Loops for < var > in <sequence>: <body> The variable after the for is called the loop index . It takes on each successive value in sequence . Often, the sequence portion consists of a list of values. A list is a sequence of expressions in square brackets. 22/02/2023 Fundamentos de Programação 48
Definite Loops >>> for i in [0,1,2,3]: print ( i ) 1 2 3 >>> for odd in [1, 3, 5, 7]: print(odd*odd) 1 9 25 49 >>> 22/02/2023 Fundamentos de Programação 49
Note: Odd is a variable (in this case) 22/02/2023 Fundamentos de Programação 50
Definite Loops In chaos.py, what did range(10) do ? >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] range is a built-in Python function that generates a sequence of numbers, starting with 0. list is a built-in Python function that turns the sequence into an explicit list The body of the loop executes 10 times. 22/02/2023 Fundamentos de Programação 51
for loops alter the flow of program execution, so they are referred to as control structures . Definite Loops 22/02/2023 Fundamentos de Programação 52
Example Program: Future Value Analysis Money deposited in a bank account earns interest. How much will the account be worth 10 years from now? Inputs: principal, interest rate Output: value of the investment in 10 years 22/02/2023 Fundamentos de Programação 53
Example Program: Future Value Specification User enters the initial amount to invest, the principal User enters an annual percentage rate, the interest The specifications can be represented like this … 22/02/2023 Fundamentos de Programação 54
Example Program: Future Value Program Future Value Inputs principal The amount of money being invested, in dollars apr The annual percentage rate expressed as a decimal number. Output The value of the investment 10 years in the future Relationship Value after one year is given by principal * (1 + apr ). This needs to be done 10 times. 22/02/2023 Fundamentos de Programação 55
Example Program: Future Value Design Print an introduction Input the amount of the principal (principal) Input the annual percentage rate ( apr ) Repeat 10 times: principal = principal * (1 + apr ) Output the value of principal 22/02/2023 Fundamentos de Programação 56
Python Programming, 3/e 57 Example Program: Future Value Implementation Each line translates to one line of Python (in this case) Print an introduction print ("This program calculates the future ") print ("value of a 10-year investment.") Input the amount of the principal principal = eval (input("Enter the initial principal: ")) 22/02/2023 Fundamentos de Programação 57
Example Program: Future Value Input the annual percentage rate apr = eval (input("Enter the annual interest rate: ")) Repeat 10 times : for i in range(10): Calculate principal = principal * (1 + apr ) principal = principal * (1 + apr ) Output the value of the principal at the end of 10 years print ("The value in 10 years is:", principal) 22/02/2023 Fundamentos de Programação 58
Example Program: Future Value # futval.py # A program to compute the value of an investment # carried 10 years into the future def main(): print("This program calculates the future value of a 10-year investment.") principal = eval (input("Enter the initial principal: ")) apr = eval (input("Enter the annual interest rate: ")) for i in range(10): principal = principal * (1 + apr ) print ("The value in 10 years is:", principal) main () 22/02/2023 Fundamentos de Programação 59
Example Program: Future Value >>> main() This program calculates the future value of a 10-year investment. Enter the initial principal: 100 Enter the annual interest rate: .03 The value in 10 years is: 134.391637934 >>> main() This program calculates the future value of a 10-year investment. Enter the initial principal: 100 Enter the annual interest rate: .10 The value in 10 years is: 259.37424601 22/02/2023 Fundamentos de Programação 60
In the next chapters... Propoer output: 134.39 instead of 134.391637934 Graph Better result Evolution 22/02/2023 Fundamentos de Programação 61
22/02/2023 Fundamentos de Programação 62
22/02/2023 Fundamentos de Programação 63
Notes on listings Listings were presented in Courier New bold, whenever posssible and survived Power point destroys indentention (remember that) Pretty listings are obtained through the use of Latex + pretty listing Screen grab from compiler Diagrams app.diagrams.net Lucidchart miro.com/flowchart-maker / 22/02/2023 Fundamentos de Programação 64
Remember Python 22/02/2023 Fundamentos de Programação 65
# Identify the code Date the code C an be used to explain Python code. Comments can be used to make the code more readable. Comments can be used to prevent execution when testing code. 22/02/2023 Fundamentos de Programação 66
Comments ''' This is a multiline comment . ''' # This is a comment. # This is a comment, too. # This is a comment, too. # I said that already. 22/02/2023 Fundamentos de Programação 67
Range To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. for x in range ( 2 , 6 ): print (x) for x in range ( 2 , 30 , 3 ): print (x) 22/02/2023 Fundamentos de Programação 68
pass The pass statement is a null statement. But the difference between pass and comment is that comment is ignored by the interpreter whereas pass is not ignored. When the user does not know what code to write, So user simply places pass at that line. Sometimes , pass is used when the user doesn’t want any code to execute. So user can simply place pass where empty code is not allowed, like in loops, function definitions, class definitions, or in if statements. So using pass statement user avoids this error. for x in [ , 1 , 2 ]: pass 22/02/2023 Fundamentos de Programação 69
for letter in 'Python' : if letter == 'h' : pass print 'This is pass block' print 'Current Letter :' , letter print "Good bye!" Current Letter : P Current Letter : y Current Letter : t This is pass block Current Letter : h Current Letter : o Current Letter : n Good bye! 22/02/2023 Fundamentos de Programação 70
FOR A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). Works more like an iterator method. fruits = [ "apple" , "banana" , "cherry" ] for x in fruits: print (x) if x == "banana" : break 22/02/2023 Fundamentos de Programação 71
...Break With the break statement we can stop the loop before it has looped through all the items: fruits = [ "apple" , "banana" , "cherry" ] for x in fruits: print (x) if x == "banana" : break 22/02/2023 Fundamentos de Programação 72
...Continue With the continue statement we can stop the current iteration of the loop, and continue with the next: fruits = [ "apple" , "banana" , "cherry" ] for x in fruits: if x == "banana" : continue print (x) apple cherry 22/02/2023 Fundamentos de Programação 73