COMSC 101 Programming Exercises, For FA15



Similar documents
COMSC 100 Programming Exercises, For SP15

Website Development Komodo Editor and HTML Intro

Exercise 4 Learning Python language fundamentals

Introduction to Python

Introduction to MS WINDOWS XP

Q&As: Microsoft Excel 2013: Chapter 2

BIGPOND ONLINE STORAGE USER GUIDE Issue August 2005

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

EXCEL PIVOT TABLE David Geffen School of Medicine, UCLA Dean s Office Oct 2002

Getting Started with WebSite Tonight

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Jadu Content Management Systems Web Publishing Guide. Table of Contents (click on chapter titles to navigate to a specific chapter)

Enterprise Asset Management System

MS Access: Advanced Tables and Queries. Lesson Notes Author: Pamela Schmidt

ITS Service Delivery ITSM & ITAM Services. Remedy FAQs. Frequently Asked Questions, Tips, and Tricks for using Remedy ITSM 7.6

How to Create and Send a Froogle Data Feed

Unit 1 Number Sense. In this unit, students will study repeating decimals, percents, fractions, decimals, and proportions.

Installing Windows 7. On your Samsung NC10

Decimal Notations for Fractions Number and Operations Fractions /4.NF

Lecture 2 Mathcad Basics

LESSON 4 - FILE MANAGEMENT

Computer Programming In QBasic

Introduction to Microsoft Excel 1 Part I

THE WINNING ROULETTE SYSTEM.

Sendspace Wizard Desktop Tool Step-By-Step Guide

How to Configure Outlook 2013 to connect to Exchange 2010

Creating APA Style Research Papers (6th Ed.)

Hypercosm. Studio.

quick start guide A Quick Start Guide inflow Support GET STARTED WITH INFLOW

Introduction to Microsoft Excel 2007/2010

Introduction to Microsoft OneNote

Getting Started with Excel Table of Contents

Windows File Management A Hands-on Class Presented by Edith Einhorn

Creating and Using Databases with Microsoft Access

So you want to create an a Friend action

Introduction to MS EXCEL 2007 Data entry & formatting Using formulas & functions Presenting data with charts Database features in Excel

Vodafone PC SMS (Software version 4.7.1) User Manual

A computer running Windows Vista or Mac OS X

How to Make the Most of Excel Spreadsheets

What is a database? The parts of an Access database

ACADEMIC TECHNOLOGY SUPPORT

Lab 9 Access PreLab Copy the prelab folder, Lab09 PreLab9_Access_intro

Microsoft Access 3: Understanding and Creating Queries

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Presentations and PowerPoint

Managing Files. On a PC, after you find your file, right click it and selet Rename from the pop-up menu.

Databases in Microsoft Access David M. Marcovitz, Ph.D.

Section 1.5 Exponents, Square Roots, and the Order of Operations

Base Conversion written by Cathy Saxton

HOW TO BURN A CD/DVD IN WINDOWS XP. Data Projects

(These instructions are only meant to get you started. They do not include advanced features.)

If you know exactly how you want your business forms to look and don t mind

3. Add and delete a cover page...7 Add a cover page... 7 Delete a cover page... 7

Excel 2007 A Beginners Guide

PharmaSUG Paper QT26

To launch the Microsoft Excel program, locate the Microsoft Excel icon, and double click.

DbSchema Tutorial with Introduction in SQL Databases

SES Project v 9.0 SES/CAESAR QUERY TOOL. Running and Editing Queries. PS Query

Using Mail Merge in Microsoft Word 2003

EXCEL FINANCIAL USES

The Social Accelerator Setup Guide

About the HealthStream Learning Center

How to Create a Spreadsheet With Updating Stock Prices Version 3, February 2015

TLMC WORKSHOP: THESIS FORMATTING IN WORD 2010

Finding and Opening Documents

Pre-Algebra Lecture 6

Hosting Users Guide 2011

DVR GUIDE. Using your DVR/Multi-Room DVR WAVE-123 wavebroadband.com

WinAntiRansom Fast-Start Guidelines

STATGRAPHICS Online. Statistical Analysis and Data Visualization System. Revised 6/21/2012. Copyright 2012 by StatPoint Technologies, Inc.

CONVERSION GUIDE Financial Statement Files from CSA to Accounting CS

File Management Where did it go? Teachers College Summer Workshop

How to Build a Form in InDesign CS5

Cal Answers Analysis Training Part I. Creating Analyses in OBIEE

Installing Windows 7. On your Samsung R519

HIT THE GROUND RUNNING MS WORD INTRODUCTION

Client Marketing: Sets

Ayear ago, I wrote an article entitled

Windows, Menus, and Universal Document Shortcuts

Step 6: Conversion to PDF

Timed Organizer User s Manual

Converting an Excel Spreadsheet Into an Access Database

Create a GAME PERFORMANCE Portfolio with Microsoft Word

Deposit Direct. Getting Started Guide

Offline Files & Sync Center

Microsoft Access 2010 Part 1: Introduction to Access

FreeAgent DockStar Network Adapter User Guide

Excel 2003 A Beginners Guide

Raptor K30 Gaming Software

Everything you wanted to know about using Hexadecimal and Octal Numbers in Visual Basic 6

2: Entering Data. Open SPSS and follow along as your read this description.

INTRODUCTION TO & BASICS

Microsoft Office. Mail Merge in Microsoft Word

Web Ambassador Training on the CMS

Programming in Access VBA

Lesson 2. From computer to USB

Year 8 KS3 Computer Science Homework Booklet

Horizon Debt Collect. User s and Administrator s Guide

Windows XP File Management

Chapter 2: Software Development in Python

Transcription:

COMSC 101 Programming Exercises, For FA15 Programming is fun! Click HERE to see why. This set of 10 exercises is designed for you to try out programming for yourself. Who knows maybe you ll be inspired to pursue study in computer science. At least you ll gain an appreciation for discipline, exactness, patience, and attention to detail that it takes to be a programmer. In any case, learning to program can help you develop problem-solving skills. As you go through these assignments, take the time to: understand the problem before you start doing any programming read all instructions first, complete one step at a time and make sure it s correct before starting the next step, know when to take your losses remember you can always start over if you get hopelessly lost. In order to develop any useful understanding of programming, it is necessary to actually do some programming. That s what this series of exercises does it provides a structured, step-by-little-step sequence for learning basic programming steps. If you are diligent, read thoroughly, and precise, you will go easily from one exercise to the next, learning a bit more each time. Python 3 The exercises in this series are designed using the Python 3 computer programming language. There are two ways to work with Python one that requires only a browser and an Internet connection, and another that requires installation of software on your computer but needs no internet connection after that. Your instructor will guide you in making your choice between the two. To use a browser, you ll go to www.repl.it/languages/python3, and you ll create your programs and run them directly on that website s home page. The advantage of using a browser is that you can work anywhere there is an Internet connection. The disadvantage is that Internet connections can be lost or can time out. We ll refer to this way of working with Python as repl.it. To use installed software, you ll first have to download and install Python itself, and a program called PyCharm which does what the browser page does. In DVC s computer labs, these are already installed. If You Get Stuck You may struggle with some of these assignments. That s normal it s part of the learning process. When it happens do this: start the assignment over from scratch, and repeat this process until you complete the assignment without struggle. Do this before going to the next exercise, because each new exercise builds on what you learned from the previous ones. And click HERE for FAQs that may help you get unstuck. Online students: Contact your instructor for help before spending a lot of time in trial and error and becoming frustrated. Remember that this is supposed to be a positive experience of learning some basics of how computer programming works. There are many conceptual hurdles to overcome throughout this series of exercises, and your instructor is here to help you over them. Face-to-face students: These exercises are meant to be completed during the lab period of your regular scheduled class time, with the help and supervision of your instructor. Seek your instructor s help whenever you find yourself struggling with understanding the requirements of an exercise or if things are not working for you. These exercises are not really designed for you to do outside of class on your own, so if you work on any at home and run into difficulty, bring it to class so that you can get it resolved. Comsc 101 Page 1 of 21 Programming Exercises

EXERCISE 1a: Using The Internet Browser To Write And Run Python Programs [hello.py] Purpose. The purpose of this exercise is to make sure you can access and use repl.it. Your instructor may direct you to skip this exercise and go to exercise 1b instead, using only PyCharm. Requirements. On a Windows PC or on a Mac, open the Internet browser of your choice. Make sure you have access to the Internet, and go to this URL: You should see something very much like this: www.repl.it/languages/python3 Exploring. If so, type this in the edit box next to the 1 : print ("Hello World") including the quote marks and parentheses. Then click to run the program, and you should see this in the output box note Hello World! : So already you have seen what a Python program looks like, you ve run a program that you typed into what we call the edit box. And we saw what actual output looks like, in what we call the output box. Good start! Experimenting. Play around with this try typing different text in the print statement of the code, and run observe the output. Add more print statements above or below the one with Hello World! see what output you can produce. Be sure to fully left-justify each print statement! HINT: To add another print statement, copy/paste/markup the existing print ("Hello World") statement do not type it from scratch! This helps to avoid typing errors. Your Turn. Here s the exercise in the edit box, insert two blank lines above the print statement you typed earlier, just like you would insert a line in any text editor. In the new line 1 type a hash symbol (#) and a space, and type your name and student ID. Comsc 101 Page 2 of 21 Programming Exercises

Starting in line 2, type additional comments as directed by your instructor. Remember to use the hash symbol at the start of each comment! Write as many comments as necessary, and leave one blank line after the last comment for spacing. Starting after the blank line that follows the comments, enter one or more print statements, printing the text that your instructor assigns. It may include your name, something about yourself, something about the class or the assignment -- however your instructor directs you. About that print statement the space before the opening parenthesis is not required. And the double-quotes can be single quotes. These are your choices pick a way and stick with it. Submitting Your Work. Your instructor may just want to see your working program in the lab, and check you off without submitting the file. Or they may require that you submit the program in printed or electronic form. In any case, you will certainly want a backup of the program you wrote, because once you close your browser, all you typed will be lost! So save it to a file: To save your work to a file, open Notepad++ or Windows 8 Notepad or Mac TextEdit (formatted to make plain text ). With that running in one window, navigate back to Python browser page and select and copy the contents of the edit box. Navigate back to Notepad or TextEdit and paste. Save it with a name as specified by your instructor. That s the file you will submit. Avoid Microsoft Word, or any rich-text editor (like Mac TextEdit formatted to make rich text ). These can lose line breaks or insert extra ones when copied back into the edit box. If you have any further work to do on the file any more programming to do anything your instructor wants you to fix then open the file, select/copy its Python program, and paste it all into the edit box of the browser page, and just continue from there. HINT: To clear the output box, click at the top middle of the output box. HINT: If you cannot see the button, try widening your browser window, or try making the edit box wider by grabbing and dragging its border with the output box. TIMING OUT. If you wait too long without doing anything, repl.it times out. If this happens, select your program in the edit box using ctrl-a (or command-a) and copy it using ctrl-c (or command-c), then refresh the page with ctrl-r (or command-r). When the page reloads, click in the edit box and do ctrl-p (or command-p) to paste and restore your program. Then proceed as normal. Comsc 101 Page 3 of 21 Programming Exercises

EXERCISE 1b: Using PyCharm To Write And Run Python Programs [hello.py] Purpose. The purpose of this exercise is to make sure you can access and use PyCharm. Your instructor may direct you to skip this exercise and use only repl.it instead, per exercise 1a. PyCharm Installation for Online Students. Before you can use PyCharm, you ll need to install it. There are two separate installations one for Python 3 and one for PyCharm. To install Python 3, go to https://www.python.org/downloads and choose Download Python 3.4.3. Then scroll down to the Files section and select the installer file that matches your system. There s one for older Macs (32- bit) and one for newer Macs (64-bit). There s one for older Windows PCs (x86 MSI) and one for newer (x86-64 MSI). Select all defaults during the installation process. Once that s done, go to https://www.jetbrains.com/pycharm/download and download the Windows or Mac version of the Community Edition. Select all defaults during the installation process. Then you should be able to find PyCharm in your Windows PC start menu or your Mac Applications folder. Starting PyCharm In Windows 7. The DVC computer labs are Windows 7 PCs. An easy way to start PyCharm is to use the start menu and type pycharm in to the search box. Then click JetBrains PyCharm Community Edition 4.0.6. On any other Windows system, find the (JetBrains) PyCharm icon and double-click that. It could be on the desktop or in the start menu or in the Program Files folder on the C drive. On a Mac, double-click PyCharm CE.app in the Applications folder. There are Python icons, too, but you ll not need to use them. Creating a PyCharm Project. You may be prompted to create a new project. If so, choose Create New Project. Good Locations for projects are your flash drive or your desktop in a new folder named python. And make sure that the Interpreter: is 3.4.3 or 34: Comsc 101 Page 4 of 21 Programming Exercises

Creating a Python Program. If all this works, you should see something like this, with the name and location of the folder you selected when you created your project: Right-click over the folder name and you ll see a popup window. Choose New and the File not Python File. Name it hello.py. Then choose the file named hello.py and select it in the left-side navigation window of PyCharm: You are now ready to create and run your first Python program! See the window on the right side of the screen with the hello.py label? That s where you ll type your program. It will be stored in a file named hello.py in your python folder. Exploring. Type this in the hello.py box: print ("Hello World") including the quote marks and parentheses. Then click to run the program. Actually, the might be grayed out and not work the first time you try it. In that case, choose Run from the Run menu: and then choose hello and run in the popups that follow. Now it should run, and should work from now on. Once you get this all to work, you should see this in the Run box : Hello World. One nice thing about PyCharm is that all of this looks the same on any system. Here are two screen shots, one from an old Windows XP installation, and one from a new Mac install: Comsc 101 Page 5 of 21 Programming Exercises

So now you have seen what a Python program looks like, you ve run a program that you typed into what we ll now call the edit box. And we saw what actual output looks like, in what we ll now call the output box. Good start! Line Numbers. Your Python program is only one line long. In the rest of the exercises in these series, there will be way more than one line! So it would be nice if PyCharm could display line numbers. To do this, use the View menu and select Active Editor, Show Line Numbers : Now the edit box should look like this note the 1 in the left-side margin: Comsc 101 Page 6 of 21 Programming Exercises

Experimenting. Play around with this try typing different text in the print statement of the code, and run observe the output. Add more print statements above or below the one with Hello World! see what output you can produce. Be sure to fully left-justify each print statement! HINT: To add another print statement, copy/paste/markup the existing print ("Hello World") statement do not type it from scratch! This helps to avoid typing errors. Your Turn. Here s the exercise in the edit box, insert two blank lines above the print statement you typed earlier, just like you would insert a line in any text editor. In the new line 1 type a hash symbol (#) and a space, and type your name and student ID. Starting in line 2, type additional comments as directed by your instructor. Remember to use the hash symbol at the start of each comment! Write as many comments as necessary, and leave one blank line after the last comment for spacing. Starting after the blank line that follows the comments, enter one or more print statements, printing the text that your instructor assigns. It may include your name, something about yourself, something about the class or the assignment -- however your instructor directs you. About that print statement the space before the opening parenthesis is not required. And the double-quotes can be single quotes. These are your choices pick a way and stick with it. Submitting Your Work. Your instructor may just want to see your working program in the lab, and check you off without submitting the file. Or they may require that you submit the program in printed or electronic form. In any case, you will certainly want a backup of the program you wrote, because once you close your browser, all you typed will be lost! The file to submit is the hello.py file that s in the python folder on your desktop or flash drive. You can navigate to it normally, or you can use a really handy feature of PyCharm for saving files simply click and drag the file from the left-side navigation window and drop it anywhere else! Use this method to copy the file to your desktop or any folder or device you wish. Your instructor may direct you to rename your Python files before submitting them in D2L, by adding.txt to the end. Rename a copied file by clicking the file s icon to select it, and then click over its name. You can rename the file as you wish. In this case, you d rename the copied hello.py to hello.py.txt before submitting it using D2L. The Remaining Execises. Now that we have two ways to work in Python -- repl.it and PyCharm there are two ways that the screen shots will look. Rather than including screen shots from both in the remaining exercises, only the repl.it shots are included in the writeups. Both have an edit box and an output box so the repl.it screen shots are easily understood by PyCharm programmers. The title of each exercise includes the file name that you should be using in PyCharm for that exercise, like this: Comsc 101 Page 7 of 21 Programming Exercises

EXERCISE 2: Using Variables And Code Blocks In Programming [me.py] Purpose. The purpose of this exercise is to introduce the concept of variables, which are capable of storing and recalling data, like the memory register on a calculator. Background. The comments and the output-producing print statements are separate blocks of code called code blocks. They are separated with a blank line, although that is just cosmetic. For this exercise, we ll introduce another code block. It comes between the comments code block and the output code block. It s the variables code block. Here s a sample code block: Like the print statements, these statements have to be fully left-justified. Each line creates a variable and stores an item of data in that variable. The sample above creates two separate variables. The word to the left of the equals sign is the variable name. The text inside the single quotes is what gets stored in the variable. Referring to it by its name, as in this sample, retrieves and substitutes a variable s content. Just a few rules variable names cannot have spaces in them, or any other punctuation (except underscore). They can only consist of letters and digits (and underscores) but cannot begin with a digit. The content of the single quoted text can be anything, as long as it s all on one line anything but a single quote! So Python allows either single or double quotes for text so we can do this: Print statements can output more than just one thing. Just list them, separated by commas, like this: By referring to a variable by its name, you get a copy of its contents. Mix and match text (offset by single or double quotes) and variables, as many as you want, separated by commas. Step-By-Step. The best way to build a program with variables is to start with just one variable. Then work that variable into your output code block. If that works, add another variable, and continue oneat-a-time until you get the hang of this. So if you intend to have variables for your first and last names, create one for your first name only and make that work. Only then, proceed to your last name. This is what we call an organic approach to programming because it grows a larger program a little at a time. Learn this approach in this exercise and apply it in all the rest of these exercises. Your Turn. Here s the exercise: use your exercise 1 file as a starting place. Following the step-bystep approach, build a variables code block with variables for your first name, last name, and any additional variables specified by your instructor. Name the variables as you wish, or as instructed. Then wherever the text from any of these variables appears among the print statements, edit those print statements so that they use the variables in place of the text. That is, if your first name is Ishmael, and it s stored in a variable named first, and the word Ishmael appears in a print statement like this: print('call me Ishmael'), then write this instead: print('call me', first). Don t worry about spacing Python handles that. Submitting Your Work. Submit your work as you did in exercise 1, following any additional requirements that your instructor may specify. Comsc 101 Page 8 of 21 Programming Exercises

Samples. Here are some samples that show how to organize the three code blocks comments, variables, and output: And here s what a typing error looks like note that the variable name for the car s year is spelled differently in the variables block that it is in the output block. Python blames the error on the second spelling. Note that Python explains the error and even says the line number containing the error. Comsc 101 Page 9 of 21 Programming Exercises

EXERCISE 3: Writing An Interactive Program With Input Prompts [echo.py] Purpose. The purpose of this exercise is to introduce the concept of input, in which a user of your program types text in the output box in response to prompts that your program prints. This one adds an input statement, which you ll use in several of the remaining exercises in this sequence. This kind of program is called interactive because its input is supplied by a user, and not by the programmer (you). By contrast, the input you typed in exercise 2 is called hard-wired it was typed by the programmer (you), directly into the program. Background. Just read -- your turn's coming! You learned in exercise 2 how to create a variable and store text in it. You also learned how to retrieve a copy of that text from the variable. But you have to edit the program every time you want to change any of the values you stored in the variables. It would be nice if you could type those values in response to a prompt, and get your program to pull them from there. Then you can use the same program, without modification, with any set of input values. Here s how it s done. Instead of typing a value in quotes, use an input statement, like this: When you run, the program will pause there and show this in the output box do what it says: type your name, then press ENTER: If you use input(" ") more than once, it just goes through the prompts one at a time. Your Turn. Now it's your turn! The application for this exercise is to write a program that produces a form letter, informing a raffle winner of their prize. There are two variables (the winner s name and the raffle prize). All the rest of the text in the print statements is boilerplate that is, it s the same text for all prize winners. Develop this program organically, step-by-step. Remember that in the organic approach, the program starts from very simple beginnings usually a copy/paste/markup of a previous working program. Then add features one-by-one, testing and confirming each change. Here are the steps to write the program for this exercise, using this technique. Comsc 101 Page 10 of 21 Programming Exercises

Step 1, write a full form letter without any variables, to print something like this: print('congratulations, Pat Student! You won our weekly computer science department raffle. Your prize is a live six-foot python. Please collect your prize at the division office before the end of the week') That s one very long line that the edit box automatically wraps for you, so do NOT put in your own line breaks. Run it and make sure it all works. Then apply one or both of the following options. Step 2, Think up prompts that you want to use for getting input something like Enter the winner s name or Who are you?. And What s the prize? or The prize is. Don t put these in the program yet just write them down someplace, so that when you need them in the Python program, they re already thought out. Step 3, Create a variables code block in the edit box. In it, #write input statements to get the name and prize using prompts. To make sure it works, put simple print statements at the end of the variables code block to print the two variables. If they are right, remove those print statements they were only to confirm things are working so far. Step 4, replace the winner s name wherever it appears in the print statement. Replace it with the variable that stores the copy of the winner s name as input. Something like print('congratulations,', winner, 'You '). Make sure it works. Step 5, replace the prize wherever it appears in the print statements, as you did the winner. If you did this right, you should be able to change the winner and prize every time you run the program, without rewriting a single thing in the program itself! Comsc 101 Page 11 of 21 Programming Exercises

Submitting Your Work. Submit your work as you did in previous exercises, submitting the contents of the repl.it edit box, or the PyCharm echo.py renamed as echo.py.txt. Here s a sample: HINT: Do not type all five input statements and then start typing the output statements. Instead type ONE input statement and see if it works that is, runs and prompts you. THEN add a print statement to echo back what got entered make sure that works right. THEN go back and add the SECOND input statement, and fully test it before adding the third, and so on. HINT: Avoid typing a variable s name more than once. Copy/paste it instead. This avoids misspellings which lead to incorrect results or errors when the program runs. HINT: Case matters in programming. myname with an uppercase N is not the same as myname with a lowercase n. Think of the alphabet as having 52 distinct characters a-z and A-Z instead of the usual 26. Comsc 101 Page 12 of 21 Programming Exercises

EXERCISE 4: Doing Text Concatenation [greeting.py] Purpose. The purpose of this exercise is to show how text stored in variables can be concatenated, or joined, to form new text sequences. It allows you to control spacing! This introduces a new code block that comes between the variables code block and the output code block. It s the calculations code block. It creates additional variables, but their values are not hardcoded, and not interactive (from input statements). They are calculated based on values stored in other variables. Background. Here s how to concatenate variables containing text. Presuming that the variables myfirstname and mylastname already exist, we can create new variables like this: Then you can simply print one of these new variables, like this: print(myname). Note that concatenation does not include spacing like the print statements with multiple, commaseparated values does. So the programmer has to put these in, like the text with one spacebar character separating first and last name above, and the space after Ms. above. Your Turn. Rewrite the program from exercise 3 so that there are no print statements with multiple, comma-separated values. Create concatenated variables in a calculations code block to combine into new variables what s in each of exercise 3 s print statements. Even if a print statement has just one text value (like print('congratulations!')), store that is a variable in the calculations code block. Each print statement should print a variable, only. Don t get the idea that print statements should always print just variables, and that text should always be concatenated for later printing that s not the case at all. We re just doing so here in order to show how concatenation works. Submitting Your Work. Submit your work as you did in previous exercises, submitting the contents of the repl.it edit box, or the PyCharm greeting.py renamed as greeting.py.txt. Here s a sample of edit and output boxes with prompts: Comsc 101 Page 13 of 21 Programming Exercises

EXERCISE 5: Doing The Math [c2f.py] Purpose. The purpose of this exercise is to show the difference between two types of data text and numbers, and how math computations can be performed with numbers. It also demonstrates how comments can be placed anywhere not just in the comment block. See the sample below. Background. In all previous exercises, the input got read as text. That s the default for Python. Even if the text involves digits and is intended as a number, it is still just text. That is, the computer does not distinguish between letters and numbers on the keyboard it s all just series of keystrokes. Remember adding the first and last names in the previous assignment? Adding 1 and 1 in the same way would result in 11. Try this: To specify that a variable should store a number, do something like this, with float( ): float is an abbreviation for floating point number. The floating point is the decimal in numbers that have a fractional part like 1½ is 1.5, and the period in 1.5 is the floating point. Your Turn. Write a program that converts a temperature (from an input prompt) from degrees Centigrade to degrees Fahrenheit. The calculation is f = 9 * c / 5 + 32, where c is the temperature in degrees C (the input), and f is degrees F (the output). You recognize the plus sign, but what are these others the slash and the asterisk? / is for division; * is multiplication. This multiplies 9 times degrees C, divides that result by 5, and then adds 32. Your output should look like this: 100.0 degrees C equals 212.0 degrees F. It should echo Comsc 101 Page 14 of 21 Programming Exercises

the value read from an input prompt (in this case, 100.0) and print the calculated variable (here, 212.0), with nice labeling to identify each. Check your work by comparing these easy reference points: -40C is -40F (the only point where C and F are the same), 0C is 32F (the freezing point of water), and 100C is 212F (the boiling point of water). Submitting Your Work. Submit your work as you did in previous exercises, submitting the contents of the repl.it edit box, or the PyCharm c2f.py renamed as c2f.py.txt. Comsc 101 Page 15 of 21 Programming Exercises

EXERCISE 6: Statistics Calculations Finding An Average [sum.py] Purpose. The purpose of this exercise is to provide more practice in writing programs that (1) read numbers from an input file, (2) perform calculations, and (3) show output results. Background. You know how to read multiple values from an input file. You know how to store them as numbers. You know how to addition, multiplication, and division. And you know how to echo input values and print calculated results. That s all you need to know in order to do this exercise. Your Turn. Write a program that reads five numbers from input prompts, adds them to get their total, and calculates their average by dividing their total by 5. For these numbers, use the present temperatures from 5 different cities in the world degrees C or F your choice. The output should something like this: But wait let s do something about all those zeros! Here s how to round off a number to a maximum of two decimal digits, using a variable name average for storing the calculated average: Statements like this belong in the calculations code block, after the variable average gets calculated and before average gets printed in the output code block, like this: This is the first time we re seeing a calculation that has the same variable name appearing twice. In this case, the original number stored in average (in this case, 73.96000000000001) gets replaced with an updated, rounded-off value (in this case, it should be 73.96). Apply this, so that your program shows something like this: I also rounded the total to one decimal digit before printing it, using the following: notice the pattern? Submitting Your Work. Submit your work as you did in previous exercises, submitting the contents of the repl.it edit box, or the PyCharm sum.py renamed as sum.py.txt. Comsc 101 Page 16 of 21 Programming Exercises

EXERCISE 7: Introducing if Logic -- Programming An RPN Calculator [calc.py] Purpose. The purpose of this exercise is to introduce logic into your programs. We ll enter two numbers number using input prompts, and use a 3 rd prompt to tell the program what to do with the first two. Background. We ve learned about comments, variables, calculations, input statments, and print statements. Fun, but it s nothing we couldn t already do in Excel. It starts to get interesting when we start using Python s if-statement. An RPN calculator uses reverse Polish notation. It s not like the calculators we use today, where we add one and one using this sequence: one, plus, one, equals. In RPN, as the earliest digital calculators used, that sequence is one, one, add. We can write a program to input two numbers, followed an instruction (like add ). It s like saying 1, and another 1, now add them. We know how to input numbers into variables using prompts (and float( )). We can even input an instruction and store it in a variable as text. But what then? Here s how if-statements work in Python: There s a lot of detail here, but it s not too bad once we break it down. It s located in the calculations code block. dothis is the variable name used to store the instruction. Then == (double-equals) is the symbol for comparing two things to see if they are equal, in this case, what s stored in dothis and the word add. Note these details: the spelling and casing of the word if, the parentheses, and the colon at the end. It all means that if the inputted instruction is add, spelled and cased exactly like that, then do all the statements indented under the if-statement. Otherwise, skip them entirely. For the two indented statements, note these details: they are both indented the same number of spaces. (The if-statement itself is not indented at all.) Both statements create new variables, just as if they were not indented and located in the variables code block. The numeric variables have to be converted to text using str(...) so that they can be used in text concatenation. The new variable saythis gets printed later in the output code block. Your Turn. Write a program that gets two number using input statements (with nicely stated prompts), and the inputs an instruction. The program should perform that instruction on the two numbers and output a nicely formatted version that echoes the input numbers and the result. The operations to include are: add, subtract, multiply, divide, average, min, and max. The Python symbol for subtraction is (as you might have guessed) is (hyphen or minus). The others we saw in the temperature conversion exercise: plus ( + ), multiply ( * ) and divide ( / ). Comsc 101 Page 17 of 21 Programming Exercises

Here are sample input sequences that your program should be able to process correctly: Use the organic method to create this program. To do so, start with just one operation add. Make this work for add. Once it s all working, put the next operation in multiply. Then subtract, then divide, then average, then min, then max, making sure to fully test your program each time you add one. Add and multiply are straightforward. The order of the numbers on lines 1 and 2 don t matter. But subtract and divide are a bit trickier subtraction subtracts the number from line 2 from the number in line 1. Division divides the number in line 1 by the number in line 2. Order matters! Average is just the sum divided by two, but be careful! It s not a + b / 2 as you might expect! Python scans the line and does all the multiplies and divides first, and then it takes a second pass and does the adds and subtracts. The above would divide b by 2 and add a to that result! So do this in two separate statements one that gets the sum and another that gets the average, using that sum. It s just like the addition example given above, but insert a new, indented line between the other two that says result = sum / 2. Max (return the maximum) and min (return the minimum) require logic inside logic! And they involve if-statements that don t just check for equality. The symbol to compare for equality is ==. To check if a number is less than another, it s <, and greater than is > as you might have guessed. Submitting Your Work. Submit your work as you did in previous exercises, submitting the contents of the repl.it edit box, or the PyCharm calc.py renamed as calc.py.txt.. Be sure to name the operations exactly as specified here, because your instructor will be testing with those names! Comsc 101 Page 18 of 21 Programming Exercises

EXERCISE 8: Statistics And if Logic Finding The Largest And Smallest Of 5 Numbers [tix.py] Purpose. The purpose of this exercise is to gain more experience with logic in your programming. Background. The way a computer finds the smallest number among a set of numbers is to assume that the first number is the smallest. Then it compares that to each remaining number, one-by-one, and changes it s mind whenever it runs across a better answer. So if a computer had this 3-number sequence: 10, 20, 30, it would create a variable named minimum and set it to 10 the first number. Then it would compare minimum (10) to the second number, 20, and replace the value stored in minimum with 20. Then it would compare minimum (now 20) to the second number, 30, and replace the value stored in minimum with 30. The number stored in minimum (30) at the end of this process is the answer. We know how to create variables to store numbers, and we know how to read numbers from an input file and store them in the variables. We know how to write if-statements, but we ve only ever tested for equality in them. Now we ll learn to test for greater or lesser. It s something like this: For more than two numbers, just repeat the if-statement, updating minimum as needed. Your Turn. Write a program to input 5 airline ticket prices from input statements, stored in variables named as you wish. Create two new variables to track the minimum and maximum, and set them to the first input number. Then in a series of if-statements, compare to each of the other 4 inputs and update the minimum and maximum as needed. For output, echo the 5 input prices, and say the minimum and maximum, something like this: Note how Python has a bit of trouble getting the fractional parts exactly right! There s a reason why this happens in every computer language, but that s a topic for programming concepts course! Submitting Your Work. Submit your work as you did in previous exercises, submitting the contents of the repl.it edit box, or the PyCharm tix.py renamed as tix.py.txt. Comsc 101 Page 19 of 21 Programming Exercises

EXERCISE 9: Sorting A List Of Names In Alphabetical Order [names.py] Purpose. The purpose of this exercise is to gain more experience with logic in your programming. Background. Remember from exercise #7 that the way to check if the contents of two variables are the exact same is like this: In exercise 8 we learned the way to check if two variables contents are greater or less than one another is like this: The one on the left says if secondnumber is less than minimum, and the one on the right says if secondnumber is greater than maximum. To reorder a set of variables, you ll have to swap the contents until they are in order. Here s how to compare and swap two, so that the name stored in firstname precedes that stored in secondname, alphabetically: Your Turn. Write a program to input 5 names and reorder them alphabetically, and output them. To do so, follow this recipe for your calculations code block: 1. if the first name is greater than the second name, swap them. 2. if the first name is greater than the third name, swap them. 3. if the first name is greater than the fourth name, swap them. 4. if the first name is greater than the fifth name, swap them. 1. if the second name is greater than the third name, swap them. 2. if the second name is greater than the fourth name, swap them. 3. if the second name is greater than the fifth name, swap them. 1. if the third name is greater than the fourth name, swap them. 2. if the third name is greater than the fifth name, swap them. 1. if the fourth name is greater than the fifth name, swap them. Submitting Your Work. Submit your work as you did in previous exercises, submitting the contents of the repl.it edit box, or the PyCharm names.py renamed as names.py.txt. Comsc 101 Page 20 of 21 Programming Exercises

EXERCISE 10: Your Own Recipe Multiplier Program [recipe.py] Purpose. In this last exercise you get to apply all that you ve learned about programming so far, to make something useful. This program adjusts the amounts of ingredients in a recipe to make a number of servings that s different from the number of servings that the recipe makes. You ll also learn another useful application of the hash symbol for comments outside of the comment block itself, to provide a detailed description of a variable in the variables code block. Background. You know how to create variables for storing numbers, but to this point we ve only ever assigned values to the inputted variables. These examples show how to hard-wire an ingredient for a recipe, with a variable name to identify the ingredient and its unit of measure: Note that there are no single or double quote marks around the numbers. This is what tells Python that these are numbers and not text. This allows them to be used in the math calculations it s going to take to convert the amounts for a different number of servings. But first we need to know how many servings that the original recipe makes: Note the one new thing here is the hash symbol and the comment that follows it. This is a comment that s added to the end of a non-comment statement, to allow detailed description that s hard to put into a variable s name. Next we need to know how many servings we want to make, using this recipe. We can get that from an input prompt like this: Finally, here s how to convert each ingredient, and round off the result before printing it the following rounds to two decimal digits, because of the 2 inside %.2f : Something You Should Know. Rounding actually converts a value from a number to text. So if you want to use a converted value in a calculation again, you d need to use float( ) as explained in exercise 5, like this: tspsugar = float(tspsugar). Your Turn. Write a program to convert your favorite recipe. Use as many ingredients as you like, as long as it s at least three. In your output, say the name of the recipe, the inputted number of servings, and the full name and amount of each ingredient, like this: Submitting Your Work. Submit your work as you did in all previous exercises. We re done! Comsc 101 Page 21 of 21 Programming Exercises