0% found this document useful (0 votes)
36 views8 pages

ITFPlus (FC0 U61) Module2 - Unit3 LE9

Uploaded by

Patano Carl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
36 views8 pages

ITFPlus (FC0 U61) Module2 - Unit3 LE9

Uploaded by

Patano Carl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 8
Module 2/ Unit 3 Poge 170 C) — Lab 9/ Using Programming Tools In this lab, you will explore the code used in iterations of a simple Python program. Exercise 1 / Installing Programming Tools In this exercise, you will install the Python development environment and download some sample scripts. ? This lab involves downloading and installing a program from a third-party website. The authors and publisher believe the website and program to be reputable and pose no risk to your computer or personal information but cannot be held responsible for any loss or damage that may occur as a result of following the steps in this lab. if you have any concems we recommend that you do NOT proceed, 1) Open a web browser and navigate to ral 2) Click the Download Python button to download the latest version of Python for Windows. Note that the exact version of Python available may vary over time. € 20 [8 mevmannmoniaen we eee | Downloading Python. 3) When prompted, in the download bar at the bottom of the browser window, click the Save button. 4) When the file has downloaded and the security scan is complete, in the download bar, click the Run button. 5) Inthe Python Setup window, click Install Now. [B Pytnen 372Gb Sep ~ * Programming and Apo Install Python 3.7.2 (32-bit) Select Install Now to install Python with default settings, or choose Customise to enabie or cisable fstures @ Install Now CAUsenVeren\pp Data ocaProgrms\Python\ Pythond I-32 > Customize installation Cheots sition ang festuree th Py! e Dinstail launcher for all users (recommended) windows Claas pon 37 tram aw Instaling Python using the default setup options. 6) Inthe User Account Control window, click Yes. 7) Setup will continue for a minute or two. When the "Setup was successful” message is shown, click Close. 8) Inthe browser, open the following URL: https: //s3. amazonaws. com/comptia-learning/python.2ip 9) When prompted, in the download bar at the bottom of the browser window, click the Save button. 10) When the file has downloaded and the security scan is complete, in the download bar, click the Open button. 11) Click-and-drag to select the Python01 and Python02 files, and then copy them to the Documents folder. Exercise 2/ Exploring a Simple Program In this exercise, you will use the shell and editor windows of Python's Integrated DeveLopment Environment (IDLE). You will also identify some basic code constructs in a simple program. 1) Click in the Instant Search box and type idle. From the search results, click IDLE (Python 3.x 32-bit) The Python shell window opens. The shell window is used to interpret and run Python scripts and programs during development. 2) Type the following function. As you type, note how tooltips appear to help you complete the statement and how color-coding is used to validate your syntax (purple for the function name and green for the string input). print (‘Hello World’) Poge 171 Module 2/ Unit 3 Poge 172 3) Press ENTER to execute the statement. The string "Hello World” is "printed" as output to the shell Be sa 1 Shel_Debug W_ Hep e3##c0482, Dee 23 2018, 22 3) (HSE w-lSle 32 bat ie D>> pene ( Wicense(|" for more information. Lad Coke Using the shell window. 4) From the File menu, select Open. Click the Documents object then double-click the Python01 file, The program code is opened in an editor window. DB rimonaraal c rene 31.3 eggs. 7 Pres, Berton Civaclaneadeomensentetin 372 Fle fii Fema fun Optins Window Help scent Python editor window below the shell window. 5) Take a few moments to identify what each line of this program does, The line position of the cursor is shown in the status bar or you can press ALT+6 to select a particular line: © Line 1 declares a variable (user_name) and sets it to the string value "World." © Line 2 uses the print() function we saw earlier but the output is constructed from both static strings and the variable we declared, Note the use of the + sign to concatenate (join together) string literals and variables, Note also that we use double quotes to delimit the literal strings. This allows us to use the single quote (’) as an apostrophe within the string. © Inline 3, we use the input() function to set the variable to a value entered by the user, © Line 4 sets up a loop using the for statement. A variable named Programming and Apo “counter” is used to track progress through the loop. To determine the loop duration, the range() function sets an initial value of 1, an exit value of 3, and a step value of 1. The intention is to run the loop three times, but as we shall see the current code might not accomplish that. ‘© Note the use of a colon to complete the line containing the for statement. While "For" type constructs in general are common to all programming languages, this statement syntax is specific to Python. It will often be the case that you may understand the general operation of logic components, but will need to lear the specific syntax of different development languages. © Lines 5 and 6 are executed during the loop. Note that these lines are indented. In Python, indentation is used to structure the code and is critical to compilation and execution. In many other programming languages, indentation is used for clarity but whitespace is ignored by the interpreter or compiler. © Also in line 5, note the use of the str() function to convert the integer variable "counter" to a string data type. © Line 7 is executed once the loop has completed and is also the final statement in the procedure. 6) Press FS to execute the program. 7) In the shell window, respond to the prompts by typing any names you wish and pressing ENTER. 8) Count how many times the loop executes—is this a surprise? 9) Leave all the Python windows open. Exercise 3 / Using the Debugger If you need to identify a logic error in code, it is often necessary to step through program execution, Using a debugger, you can pause execution and view the values of variables at the time a particular statement is being executed. 1) Inthe editor window, right-click line 5 (the first statement in the for loop) and select Set Breakpoint. The line is highlighted in yellow. A breakpoint means that code execution will always pause at the line when the debugger is active. 2) Inthe editor window, right-click line 7 (the last line) and select Set Breakpoint 3) Inthe shell window, select Debug > Debugger. A Debug Control window opens and the shell shows the message "DEBUG ON," 4) In the editor window, press F5 to run the program. Poge 173 Module 2/ Unit 3 Poge 174 felleclesleals Ce rae = = Using the Python debugger. Because debug control is active, you now need to start execution manually. ‘The Go button proceeds normally with execution until a breakpoint is met. For this exercise, we will investigate the use of tools to step through code in increments. 5) In the Debug Control window, click the Step button The first line of the program is executed. Note that user_name is added to the list of locals (variables). 6) Click the Step button, The debugger starts executing the print() function, calling an ‘idlelib.run.write() function to do so, We don't necessarily need to view every sub-step in this—as a built-in function we can assume that it works correctly. Using the "Step into" debugger tool 7) Click the Out button. Using "Step Out" completes processing of the function and advances execution to the next statement (ine 3). 8) Click the Over button. Using "Step Over” processes the statement without pausing for each part of any functions it contains, Note that program execution is still paused on line 3 however. The input() function is waiting for user input. Note that the debugger buttons are greyed out 9) Switch to the shell window, click at the prompt, type any name, and press Programming and Apo ENTER ‘Develooment 10) In the Debug Control window, note the new value of the user_name variable, Click the Go button, Program execution is next halted by the breakpoint you set for line 5. Note that the counter variable is now listed, with the value 1 11) Click the Go button. 12) Switch to the shell window, click at the prompt, type any name, and press ENTER. 13) In the Debug Control window, Click the Out button. 14) Switch to the shell window, click at the prompt, type any name, and press ENTER 15) In the Debug Control window, click the Out button. Note the value of counter as the program exits the loop and processes line 7. Can you explain why the loop only executes twice? The Python range() function is consistent with zero-based indexing, For ‘example, an array with 10 elements includes the items 0,1,2,3,4.5,6,7,8, and 9 but not 10. The range() function is upper bound exclusive and the range we have used does not include the value 3. We can make the range() function work inclusively by adding one to the stop value. We could also just set the stop value to 4 but adding one makes the intent of the code clearer. 16) In the editor window, change the line to read as follows for counter in range(1,3+1,1): 17) Save the file then press FS to run it again. 18) Step through the program to confirm that the loop executes three times. g Another option would be to define a different variable to store the number of times the program has "met" someone. This might make the code easier to understand at the expense of making it a bit longer. 19) Take a moment to review the use of the debug tools: © Go—continue execution normally (unless a breakpoint is hit). © Step—advance through statements and functions step-by-step. This is often also referred to as "Step Into.” © Over—execute the next statement without "following" any function calls. Poge 175 Module 2/ Unit 3 Poge 176 © Out-complete any remaining parts within a function and pause at the next statement in the main program flow. 20) Close the Python editor window. 21) In the shell window, select Debug > Debugger. The debugger is disabled. Exercise 4/ Using a Function We have used a few of Python's built-in functions to write our program. Funetions are self-contained routines designed to accomplish a specific task. Functions can often be reused in different parts of the overall program. While using this basic program, you may have noticed that some of the output, is not grammatical. Rather than state "You are the 2 person I've met today" it would be better for the output to state "You are the 2nd person I've met today." To do this, we can use a function that returns the correct ordinal suffix ('th,” "st," "nd," or "rd") for a given cardinal integer. 1) From the File menu, select Open. Click the Documents object then double-click the Python02 file. The program code is opened in an editor window. Deron cmaimezanoeonar OR Ss Python program with separate functions. 2) You can see the new function has been added in the first ten lines. Note the use of "def' to declare the function and the use of indents to show which statements belong to the function. Other languages are more likely to use brackets to delimit the statements belonging within a function. The previous code has been assigned to the function main(). The last line of code calls this main() function if the script is executed directly. This structure allows the file containing these functions to be imported by another module without necessarily running the main() code. ? You might think of main() as more procedure-like than function-ike but Python doesn't distinguish between functions and procedures. A Python function does not have to return a value. It's simply a means of defining a block of code. 3) Note that line 1 contains a comment (#) with attribution for the source code that this function is derived from. 9 The original function is more concise than this version. We've added an additional step to illustrate the use of some different code operations. 4) Inline 16, note the way that the ordinal_suffix() function is called. The function expects an integer as input (an argument). The main() function is passing the value of the integer variable "counter" to the ordinal_sutfix() function 5) Inline 2 we use an array-like construction to store the list of ordinal suffixes associated with 1, 2, and 3. This type of Python list is called a dictionary, Note that the list is declared outside of any function definition, making it available to any code in the same module. 6) Look at line 3. The function assigns its own variable (j) to the integer value Note that ordinal_suffix) does not manipulate the value of the "counter" variable. 7) Look at the if conditional blocks in lines 4-9 and make sure you understand what they do: © Inthe first if statement, we check whether the integer is over two digits long. Ifit is, we truncate it, using functions to convert between integer and string and back. For example, if the value of iis 112, this statement will convert it to 12. The code snippet [-2:] is a slice, which is the method used in Python to return part of a string (in this case the last two characters). We're doing this because we only need to evaluate the values from 0 to 99 to determine the appropriate suffix. © The second if statement checks whether i has the value of 11, 12, or 13 because in these special cases, the suffix is "th” not "11st" or "12nd.” The code uses the comparison operator less than (<) to accomplish this, © The else statement retums the correct suffix in any other case. It does this by using the mod operator (%). Mod returns the remainder after division. For example, if iis 2 then the remainder after division by 10 is, also 2. Ifiis 22, the remainder is still 2. The get() function is used to lookup this remainder value in the SUFFIX_DICT list. If the value is not found (if itis zero or four for instance), "th" is returned by default 8) Use FS to run the new program and test that it returns correctly formatted suffixes in the output 9) Change the value of range (1,3+1,1) to test different integers. For ‘example, try range (109,124,1) 10) Close all open windows and apps. Poge 17

You might also like