Python Scripting

User Generated



Sessions College for Professional Design


Each of the problems below tests your ability to write basic Python scripts. Use IDLE (Python GUI) for these exercises and save your work as .py and/or .txt files as indicated in each section.

Important: Place all of your completed files for this exercise in a single ZIP file for submission to the Dropbox.

Be sure to test each of your .py script files before turning them in. If you cannot get them correct, turn in your best efforts.

Unformatted Attachment Preview

1. Experiment with the Interpreter Enter the following values and expressions, one at a time at the IDLE prompt (>>>). Observe the result. If any result puzzles you, try similar entries and see what happens. • • • • • • • • • • • 100 100 + 1 100/2 100 * 2 2**3 'hello' 'eat' + ' ' + 'at' + ' ' + 'joe's' '2' '2' + '3' True True or False Turn in a transcript of your efforts by saving a log of your interactions. Use the File > Save As command and choose .txt as the format. (You are saving a record of your interactions with the interpreter and not a script, so do not save as .py). 2. Using the Python Interpreter as a Calculator Use the Python interpreter as a calculator to solve the following problems. Turn in a "transcript" of your work with the calculator (a .txt file) with a record of your calculations. If you make a mistake, you can simply try again. You can edit out extraneous material in the .txt file, but be careful not to remove material that is necessary to verify your work. If you make a large number of errors, you may want to start over so that the version you hand in is easy to follow. Use the Python single line comment character (#) to add comments that will allow me to better understand your work. For example: >>> 12 * 9 # area of rectangle 108 Read the problem carefully. Use Python for all arithmetic calculations. Do a sanity check on each calculation. That is, if you do a rough estimate in your head or on paper, do your precise results seem in line with what you expected? Be especially careful when doing division to obtain a real number result rather than an integer. An 18 foot by 24 foot room needs its hardwood floors painted. The floor will be painted with one coat. The paint to be used covers 350 square feet per gallon. The paint is sold in gallons for $55 each. Calculate the following: a. How much floor area needs to be painted? b. How much floor paint must be purchased (in gallons)? c. How much will the paint cost? 3. Writing Hello World Traditionally "Hello World!" is the first program written by programmers learning a new language. Write you own Hello World! in Python using the print statement. Remember that your greeting must be a string. Save your program as Improve upon the "Hello World!" program by allowing for a custom greeting. Use the input function to ask the user for his or her name and to save the user input in a variable. Use the variable as the parameter to the print function to give a custom greeting. Test your work and save it as What Is a Function? Before tackling the next two parts of this exercise, let's talk more about functions. You can think of a function as a special-purpose sequence of computer code that can be called upon by name to carry out a preplanned set of actions. Some such machines can be wholly self-contained. Having no inputs, the steps they carry out are determined solely by the lines of code within the function. Other such machines, can take predetermined inputs, that allow their functioning to vary a bit. For example, imagine a function that counts the characters in a string containing text. Such a function should be set up in such a way to allow it to be reusable. Once the function is written, it should be callable over and over again with varying text strings. To write such a function, you do need to know how to implement in code the action the function carries out. The caller of this function need not know how the function does it work. The caller only needs to know what the function does, how to make the appropriate call, and what the function returns. Were you to write such a function, you would need to verify that it works as planned. This means testing it out on varying inputs. You could do so by making successive calls to the function each time with differing parameters. You might try a string with just alphabetic characters ("abcd"), one with special characters (Yikes$%#!), one with spaces ("Hello World!") and one with no characters at all (""). The latter is known as an empty string. The intent of testing is to convince yourself that the algorithm (method) chosen is the correct one and that it has been successfully implemented. 4. Creating a Function Use the code you wrote for the customized greeting to create a function called GreetUser(). You will need to use the def command for this task. Test your function by calling it at least twice with different string values as parameters. For example, one test might invoke GreetUser("Sam"). Save your work as and supply the Python log of your testing. Do so by saving the contents of the IDLE as a .txt file 5. Creating a Function with More Than One Execution Path (Optional) This part of the exercise is optional and for extra credit. Write a Python script that asks the user to guess a number between one and ten. If the user guesses correctly, he or she is congratulated. If not, the user gets a second try. This task requires that you do the following: 1. Define a function that takes as input two numbers. It compares the two and returns True if the numbers are the equal and False otherwise. (This is just a general purpose compare function that could be used for purposes other than comparing a random number to a guess.) 2. Generate a random number between 1 and 10. Use the built-in randommodule to generate your random number. You'll need to import the module and then use the randrange() function to generate the value as shown below. You will need to assign the value returned to a variable. >>> import random >>> random.randrange(1,10) 1 3. Ask the user to guess the secret number. Use input() to get the number. 4. Call the compare function with the appropriate parameters to determine if the values are the same or different. If the function returns True, meaning that the user guess is correct, the script prints a congratulatory message. If the function returns False, meaning that the user guess is incorrect, the user is allowed a second guess. Check that guess for equality with a second call to the compare function. Let the user know if the second guess succeeded or failed. Save your work as and supply the Python log of your testing. Do so by saving the contents of the IDLE as a .txt file If you can correctly complete these optional assignment, you'll get extra credit for this exercise. Important: Place all of your completed files for this exercise in a single ZIP file for submission to the Dropbox. Computer Programming Computer programming is the art of creating the software instructions that control the actions of a computer. In this lecture you will get an overview of the software development process and get the chance to develop some simple programs of your own. You will learn the fundamentals of the Python programming language, a high-level, general purpose programming language that many people use as a springboard to other programming work. At the end of the lecture, you will not be a full-fledged Python programmer, but you will have a taste of what programmers do and how programs work. As design students, this introduction to programming gives you a better sense of how your essential design software "thinks." And it helps make web scripting in HTML, CSS, and JavaScript feel more familiar and logical. Programming has come a long way from machine code and assembly language. Important: This lecture includes required reading found in this week's folder. In this lecture, you can expect to: Learn the basics of the software development process. Learn how programming evolved into the high-level languages we use today. Learn how to install and use a Python interpreter. Learn to write basic programs in Python using variables and values. Learn the basics of debugging a program. The Software Development Process Garbage In, Garbage Out Developing software requires programmers to create very detailed instructions that a computer can carry out. Computers are complex machines, but they are only capable to doing exactly what they are told to do. The old saw "garbage in, garbage out," reflects this reality. Computer programs only work well if they are well-designed and well-implemented. When computer software fails to work as planned, the problem is termed a bug. As useful software programs tend to be fiendishly complex, software is seldom bug-free. The source code written by programmers must be compiled into object code before a program can be used. Source lines of code (SLOC) measure the complexity of a program. The more lines, the more complex the program. The source code for a computer program is the form in which the programmer creates it. It is human-readable and is not executable by the computer. Object code is the file produced when the program is compiled(meaning prepared for execution). It is not human-readable. Source lines of code (SLOC) is a frequently-used measure of the complexity of a software program. This term refers to the number of lines in the programmer's source code. Using SLOC as a measure, it is clear that software has become much more complex in the past decades. In 1993, the operating system Windows NT 3.1 was estimated to have four to five million lines of code. Windows 10 is said to have about 50 million lines of code, a ten-fold increase. But Apple is not to be beat. Steve Jobs is said to have revealed in his August 2006 keynote at the Apple World Wide Developer Conference that the Mac OS X 10.4 had 86 million lines of code! Many have noted that as programs get longer they tend to get buggier. Improvements in programming languages and the software quality assurance process have offset this to some extent but not entirely. Software development is a team process which involves not just programmers but product managers, interface designers, customers, and more. The result is a set of interactions that can be fraught with miscommunication as the cartoon below illustrates. The origin of the term bug is a bit obscure but some have claimed that an actual bug crawled into an early mainframe computer and gummed up the works. Click to enlarge. Variations on this cartoon have graced the bulletin boards of software company lunch rooms for many years. Programming Languages In the early years of software development, programmers worked with tools that were very low-level and machine-specific. These days they are likely to work with tools that are high-level and cross-platform. Let's explain what these terms mean. Machine Code The first modern computers were programmed using what was known as machine code. Each line of code typically consisted of an address and the data to be loaded at that address. Each piece of data might be an instruction or one of its operands (the information on which it acts). To write machine code, a programmer needs to have a detailed understanding of the architecture of a specific machine and must learn or look up hexadecimal codes for a large number of commands. Before modern programming languages, programmers wrote machine code using a hexadecimal number system. Basic code after compilation into machine code on a Commodore computer. As one machine architecture differs from that of another manufacturer, programmers needed to learn new specialized codes each time they wanted to work with a new machine. Programs written for one machine did not work on another without a great deal of rewriting. Programming errors were easily made and hard to diagnose and fix. Assembly Code Machine code was sufficiently hard to use that programmers looked for alternatives. The first big improvement over machine code was assembly code. Assembly languages substituted mnemonic devices for hard to remember hexadecimal codes. A special program called an assembler translated assembly code into the machine code native to the device on which the code would run. Assembly languages had many advantages over machine code but were still architecture-specific, and hard to learn and debug. Assembly language and high-level languages were born out of a need to create machine code more easily. Assembly code along with corresponding machine code and register contents as seen in a Code View Debugger. (Photo credit: Microsoft) High-level Languages It was the invention of high-level computer languages that represented a major breakthrough in ease of programming and programmer productivity. Code in these languages offered a high level of abstraction from the low level details of the computer architecture, more closely resembling plain English. After such code was written it was converted to machine code by a specialized program called a compiler. Compilers freed programmers from the tedium of assembly code and brought with them specialized tools such as debuggers, software that aided programmers in figuring out where the errors in their programs were located. High-level languages also offered the promise that a program could be written once and compiled for multiple platforms using differing compilers. A chunk of code in the C# language. This chunk lists all of the files in a directory. (Photo credit: Microsoft) FORTRAN One of the first high-level languages was FORTRAN, a language developed by IBM in the 1950s for numeric computation and scientific computing. FORTRAN is an acronym or "formula translation." A simple FORTRAN program is shown below. Lines that begin with the letter C are comments and are ignored during the program's execution. But comments serve an important purpose in documenting the program's actions. C AREA OF A TRIANGLE WITH A STANDARD SQUARE ROOT FUNCTION C INPUT - CARD READER UNIT 5, INTEGER INPUT C OUTPUT - LINE PRINTER UNIT 6, REAL OUTPUT C INPUT ERROR DISPLAY ERROR OUTPUT CODE 1 IN JOB CONTROL LISTING READ INPUT TAPE 5, 501, IA, IB, IC 501 FORMAT (3I5) C IA, IB, AND IC MAY NOT BE NEGATIVE C FURTHERMORE, THE SUM OF TWO SIDES OF A TRIANGLE C IS GREATER THAN THE THIRD SIDE, SO WE CHECK FOR THAT, TOO IF (IA) 777, 777, 701 701 IF (IB) 777, 777, 702 702 IF (IC) 777, 777, 703 703 IF (IA+IB-IC) 777,777,704 704 IF (IA+IC-IB) 777,777,705 705 IF (IB+IC-IA) 777,777,799 777 STOP 1 C USING HERON'S FORMULA WE CALCULATE THE C AREA OF THE TRIANGLE 799 S = FLOATF (IA + IB + IC) / 2.0 AREA = SQRT( S * (S - FLOATF(IA)) * (S FLOATF(IB)) * + (S - FLOATF(IC))) WRITE OUTPUT TAPE 6, 601, IA, IB, IC, AREA 601 FORMAT (4H A= ,I5,5H B= ,I5,5H C= ,I5,8H ,F10.2, + 13H SQUARE UNITS) STOP END High-level languages use wording that resembles English so they are easier to write and understand. AREA= The numbers 501, 701 through 705, 777, and 799 are line numbers. The program's flow of control, that is the order in which it carries out the instructions, could be changed by branching execution to a new location within the code. FORTRAN code also featured the now infamous GOTO statement which allowed for a jump to a new location in code. The result of such coding techniques could be a hard to follow program logic sometimes termed "spaghetti code." While some programmers were skeptical about the new high-level languages, FORTRAN code was said to have reduced the number of code instructions needed by a factor of 20. FORTRAN statement ready to be input from a punch card. (Photo credit: Stack Overflow) Programming Languages Today Today nearly all programmers work in high-level languages. Improvements in programming languages have allowed programmers to focus on the logic behind programming problems rather than the machine architecture. The website ranks the popularity of programming languages. Its top 10 for 2010 are as listed below. 2018 rank 2017 rank Programming language 1 1 Java 2 2 C 3 3 C++ 4 5 Python 5 4 C# 6 6 Visual Basic .NET 7 7 PHP 8 8 JavaScript 9 12 Ruby 10 — SQL The languages that are rising in popularity include object-oriented languages (C++, C#, and C) and those widely used for web page development (PHP, Ruby). Procedural programming languages focus on the steps involved in carrying out a programming task. C and Visual Basic .NET are examples of procedural languages. Object-oriented programming, which became popular in the early 1990s, uses a programming paradigm that focuses on data rather than procedures as the key to creating discrete, reusable units of code. Learning Python All of the programming examples you will create in the exercise will be written in Python, one of the popular languages on Tiobe's list above. Python is a general purpose high-level programming language whose design philosophy emphasizes code readability. Python has an open, community-based development model. Its development is overseen by the non-profit Python Software Foundation. The Python language is interpreted rather than compiled. With compiled code, an entire program must be processed by special software termed a compiler before it can be executed. With interpreted code, each line of the code is executed as you submit it to the interpreter. With interpreted code, you can debug, that is find problems with your code as you go along rather than slogging through repeated cycles of: code, compile, test, recode, recompile, retest. Interpreting a single line of code is also much faster than recompiling a large program. Open source software products are built and maintained by a network of volunteers. The code for such software is "open" in that it is made available to all as opposed to code that is held secret as the proprietary information of a particular company. Install Python Before you can do anything with Python, you need to install the Python interpreter on your computer. Go to Scroll down to the download section and choose the appropriate version for your computer's operating system. From the Python Download page, choose the Windows or Mac installer. There are two ways to use Python: shell mode and script mode. At first, you will work in shell mode. In this mode, you type a command in the shell prompt and the Python interpreter immediately prints the result. Once you start writing longer programs, you will very likely find it advantageous to switch to script mode. In this mode, you author your program in a text file and request that the interpreter carry out the sequence of commands it that file. Whichever mode you choose, however, the net effect of running your code is the same. Launch the Python Shell Switch to Script mode when you've outgrown the Shell. To launch the Python Shell, go to your Python install location and choose IDLE (Python GUI). The Python Shell should now appear. On Windows the shell looks as shown below. If you are on a Macintosh, the windows will have a different appearance but the window content should be similar. Whatever your platform, your Python Shell will interpret code in exactly the same way. The Python Shell Once you have more experience and are writing somewhat longer programs, you should switch to the Python Script mode. In this mode you can submit whole programs for execution. You also can save your work for future use. Working with the Python Interpreter With interpreted code, you get feedback at the point at which you signal to the interpreter that you want to carry about some action. To issue a command, simply type your input at the shell prompt (>>>) and press Enter. For example, type 2+2 at the prompt now and press Enter. You will get the reply 4. >>> 2+2 4 Let's look at some of the common types of code that get entered into the Python interpreter. You do not need to understand how all of these work in detail, but getting familiar with the terms will help you in the required readings and the exercise. Code must be written carefully, with correct spelling and punctuation, for the interpreter to understand it. Values The example above uses integer values (in this case positive whole numbers). When working with Python, as with just about any programming language, you must be aware of the type of value you are working with. Python allows for a variety of value types. We will limit ourselves the following value types so we can stick to the basics: • • • Integers (such as 17, -12, 189, 21221) represent the positive and negative whole numbers plus zero. Real numbers (for example, 3.14159, 40.5) represent values which include decimal points. Note that in Python 3 integer division automatically yields a real value. Thus 5/2 return 2.5. Boolean values are either True or False. They correspond to the 1s and 0s passed to electronic circuits as described in an earlier lecture. Boolean values can be combined using operators such as and, or, and not. If you are not sure of the result of combining either of these values with any of the operators, you can simply try out the expression in the interpreter. >>> not True False >>> True or False True >>> True and False False >>> • Strings (for example, "Hello World!", "Gad zooks!", "Izzy") include alphanumerical values. Be aware the the numeric symbols (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) can be used within strings. Expressions You can use the Python interpreter much as you might a sophisticated calculator to do complex calculations. In using the interpreter as a calculator, you typically need to combine values into more complex expressions. The most basic arithmetic operators are listed below. All of the operators should be familiar except for the asterisk used in multiplication (not an x). • • • • + * / Addition Subtraction Multiplication Division The + operator can be applied to values of data type string as well as to numbers. In such cases, the operator combines (concatenates) the strings in question. Spaces are characters just like alphabetic characters and numbers. If you want a space to appear in a string, you must explicitly place it there. >>> "Hello" + " Dolly" 'Hello Dolly' >>> Unlike some programming languages, Python does not require that you declare a variable before use; that means that you don't have to tell Python about the variable before you use it for the first time. Variables Were we only to use the Python shell as a calculator, there would be severe limits on what could be accomplished. By using variables, we are able to name values and save them for later use. (Future JavaScript users, take note! You'll use variables quite a lot.) The data type of the variable (integer, real number, string) is determined by the way that you use it. In the first example below, the characters 123 are used as part of a string rather than as an integer. The example that follows used alphabetic characters (Elvis) to form a string. >>> UserId = "123" >>> UserId '123' >>> >>> UserId = "Elvis" >>> UserId 'Elvis' >>> Both examples use the equal sign (=) to denote assignment. In the above examples, the variable name UserId is assigned the value that appears to the right of the symbol. Note also, that Python allows you to use double quotes (") interchangeably with single quotes (') when defining strings. User Input Interesting programs need some source of external data. A common source is user input. >>> name = input('Your name please\n') Your name please Jane >>> name 'Jane' >>> In this example, I created a variable called name and the user is asked to enter a name that will be assigned to it. This name example is just about the most basic way to collect user input, but the idea remains the same when the input gets more complex. For example, choosing a tool in Photoshop is user input. Filling up an e-commerce shopping cart is user input. The program asks the user for information, the user provides it, and the program acts accordingly. Making Decisions If script execution always followed the same steps in the same order, there would be a serious limit on the usefulness of such programs. Fortunately scripts can vary their execution based on the value of expressions. One of the most basic ways a script can vary its execution is by using an if statement. An input to a function is known as a parameter. Functions can take zero or more parameters depending upon the task they implement. ... >>> balance = 0 >>> if balance > 0: print("You are in the black!") You are in the black! >>> If you add an else clause to your if statement, you can handle both the case where the condition (balance > 100) is True and the one where it is False. ... >>> balance = 0 >>> if balance > 0: print("You are in the black!") else : print ("Your account is running on empty!") Your account is running on empty! >>> Functions Once you create code of any significant degree of complexity, you will find that it is annoying and impractical to reenter that code every time you need to reuse it. Python allows you to attach a name to multiple lines of code making it possible to "call" that code repeatedly without reentering it. Such named code can be invoked when needed as part of a larger Python program and is called a function. The simple function shown below takes a number as its input, adds one to that number and returns the result. >>> def addOne(n): n = n + 1; return (n) >>> addOne (10) 11 >>> Creating Python Scripts So far, you have seen some commands that can be used when working with the Python Shell. Now we'll look at Python scripts. Python scripts contain these same commands, but instead allow you to run a sequence of commands without typing them in one at a time. Scripts also make it possible to save your code for later use, something that is not easily done with the shell. The Python interpreter provides for commands that make it easy to create and run scripts. Choose the New Window command from the File menu to create a new script. A new window opens in which you can write your script. Select Run Module from the Run menu to execute any code you write. Write the following in your new script: Python scripts are stored in plain text tiles with the extension .py. Enter the above code carefully. This program defines the length, width, and area, then instructs the computer to display the area. This program defines the variables "length" and "width" as numbers, and defines the "area" variable as the product of the two other variables. The "print" command tells Python to display information, in this case the value of the variable "area." Your file is not saved until you choose Save As from the File menu, and choose a name and a save location. Choose a name that is descriptive of your program's purpose. Python scripts are stored in plain text tiles with the extension .py. It is also a good idea to create a folder to store all of your Python programs. I've named my file and placed it in a folder specifically for my Python programs. Once you have saved your script, you can use the Check Module command on the Run menu to verify that your program is formally correct. If not, you will get an error such as the one shown here: Syntax errors usually mean that you mistyped some code. Runtime errors mean the code cannot be executed for various reasons. If you get this error on your sample area program, check all of your typing to make sure it is correct. The problem is that "print area" is a function and must be written "print (area)". Make the change and try again: If everything checks out OK, use the Run Module command on the Runmenu to execute your program. Note that the shell is automatically restarted when you run this command. That is, any information stored by previously given statements is flushed from memory. Here you can see the shell was restarted (== RESTART ==) and the answer to length * width was printed. You can get more information on working with the IDLE shell by choosing IDLE Help from the Help menu. In the required reading for this lecture, you will learn to write additional basic programs. Debugging Your Code All programmers make errors when coding. Experience may reduce the number of errors you make, but finding and fixing errors is a key part of a programmer's job. When you enter an invalid statement at the interpreter prompt, you will get an error message. At first, such a message may appear cryptic and unhelpful. But careful reading of the error can give you a clue as to what the problem is. In the example below, the interpreter is telling you that the statement entered does not follow the syntax rules for Python statements. In other words, it is misformed. >>> my dog is Maggie SyntaxError: invalid syntax You can also write code that is formally correct—it follows the Python syntax rules—but that cannot be executed nevertheless. These are runtime errors. A common example is using a variable that is not yet defined. In the example that follows, I am trying to calculate the area of a rectangle (length times width) but have failed to define the variable "w" before using it. >>> l = 10 >>> area = l * w Traceback (most recent call last): File "", line 1, in area = l * w NameError: name 'w' is not defined Finally, there are cases where your code runs to completion but fails to produce the expected answer. These are both the most challenging and the most interesting errors. They result from an error in thinking: The code you have written does not do what you thought it would do. Continue your Python experience with the required reading for this lecture, found in this week's folder. Follow along carefully and you'll have a head start on the next exercise!
Purchase answer to see full attachment
User generated content is uploaded by users for the purposes of learning and should be used following Studypool's honor code & terms of service.

Explanation & Answer

Hello buddy, i have finished the...

I was having a hard time with this subject, and this was a great help.


Related Tags