













Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Programming exercises for beginners to learn Python, focusing on variables and input. It explains how to save code in a file, run it in PyCharm, and understand the concept of variables. The document also covers different ways to input text and numbers, and how to concatenate variables. It is intended for university students taking a programming course.
Typology: Lecture notes
1 / 21
This page cannot be seen from the preview
Don't miss anything!














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:
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.
Inperson students: These exercises are 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 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.
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: www.repl.it/languages/Python
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.
You should see something very much like this:
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! ”:
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, then widen your browser window, or make 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.
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 (32bit) 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 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:
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:
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:
Right-
click over the folder name and you’ll s
ee 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.
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”:
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
Now the “edit box” should look like this – note the “1” in the left-side margin:
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: 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.
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.
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.
Step 1 , write a full form letter without any variables, to print something like this:
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.
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:
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:
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.
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 3rd^ 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 ( / ).
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.
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:
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. 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.