Draw a Circle at User Click Python
Goals
Upon successful completion of this lab, you lot should be able to write and alter Python program that use:
- definite loops
- ranges
- the accumulator pattern
Setup and Practice
Setup
- If your lab machine was not started in MacOS when you went to use it, get assist to reboot it to MacOS.
- Follow these procedures to mount your blue home-directory on the local auto and create a PyCharm project (phone call information technology Lab02). Y'all volition use PyCharm in the next part, but, it is of import that you set up your projection at present then that if yous run into any upshot, we can resolve them rapidly.
- Install the graphics.py library to use information technology during this lab. Meet these procedures for assistance.
Exercise
- Answer Question ane–5 in your writeup (on Moodle).
- In a new browser tab, visit the online Python 3 tutor and enter the post-obit Python lawmaking:
for i in range(3): impress('Cupcakes!')Then click "Visualize execution." - Click the "Forwards" push to step through the lawmaking, didactics by didactics. Pay attention to how the variable
ichanges (shown on the right side of that screen). -
Using the visualizer to help you, answer Questions 6 and 7 in your writeup. Pay attention to both the program output (beneath your code) and the global variables (to the right).
Hint: Your respond to Question vii should be a comma-separated listing with spaces between the values. For example:
8, ix, 10 - Now click "Edit code" in the Python visualizer and enter the post-obit code:
for j in range(two, 8): print('Marshmallows!')Visualize this lawmaking and respond Questions 8 and 9 in your writeup. - Now endeavour...
for k in range(8, 2): print('Thin Mints (TM)!')Visualize this program and answer Questions 10 and eleven in your writeup. - Now effort...
x = 5 for i in range(1, 6): x = i
Visualize this program and answer Question 12 in your writeup. - Now try...
x = five for i in range(1, 6): x = x + i
Visualize this program and answer Question 13 in your writeup. - Continue to Office A.
Part A: Sum a list of numbers
The instructions beneath will help you write a program that asks the user for 5 numbers and computes their sum and mean.
Instructions
- Open PyCharm so the projection Lab02. Create a new python file an call it lab02a.py. Copy-paste the following programme into the new window, substituting your proper name for the italicized text:
""" Program: CS 115 Lab 2a Author: Your name Clarification: This programme adds up the numbers from 1 to 5. """ def primary(): total = 0 for i in range(one, 6): total = full + i print('The total is:', total) principal() - Answer Questions 14–16 in your writeup. You lot tin use the the online Python 3 tutor to reply these questions.
- If you modified your programme to answer the questions in your writeup, change it back to the original version.
- Over the adjacent few steps, y'all will modify your program to inquire the user for 5 integers and and then print their sum. Here is an case of what your program volition eventually do:
Enter an integer: ii Enter an integer: 100 Enter an integer: -1 Enter an integer: lxxx Enter an integer: 4000 The total is: 4181 The hateful is: 836.2
If y'all feel set up to write this program, try it! If you get it working, skip to Step ix. Otherwise, work through the following steps. - Alter your original plan to prompt for an integer and read the user's input into a new variable. Put this new statement inside the loop so that it happens v times.
After you do this step only, you lot will exist asking the user for 5 integers, simply your program will still impress the sum as 15:Enter an integer: 2 Enter an integer: 100 Enter an integer: -1 Enter an integer: eighty Enter an integer: 4000 The total is: 15
- Now, change the code so that every time y'all go through the loop, instead of adding
ito the running full, y'all add together the number that the user just typed. - Verify that your program'south output matches this example:
Enter an integer: two Enter an integer: 100 Enter an integer: -i Enter an integer: 80 Enter an integer: 4000 The total is: 4181
- Compute the mean by dividing the total by five. You should only need to exercise one partition operation. Verify that your programme'due south output matches this instance:
Enter an integer: 2 Enter an integer: 100 Enter an integer: -one Enter an integer: 80 Enter an integer: 4000 The total is: 4181 The mean is: 836.2
- Demo. Call an instructor over to demonstrate your Role A code.
- Continue to Office B.
Part B: Draw arbitrary circles
For this part of the lab, you volition employ the graphics package to initially describe a bunch of circles. Afterward in the lab, we will apply loops to automatically generate multiple circles.
Instructions
- In PyCharm, create a new Python file lab02b.py. Copy-paste the following programme into the new window, substituting your proper noun for the italicized text:
""" Program: CS 115 Lab 2b Writer: Your proper noun Clarification: Using the graphics bundle, this program volition draw a circumvolve. """ from graphics import * def master(): window = GraphWin("Circles", 800, 800) center = Point(100, 200) # create a point to serve as the center of the circle radius = 40 circumvolve = Circumvolve(center, radius) # create a circle centered at "center" with radius "radius" circle.setOutline('bluish') circle.describe(window) # draw the circle in the window that we created earlier window.getMouse() # wait for the mouse to be clicked in the window window.close() # close the window after the mouse is clicked in the window main() - Run the programme. Y'all should see a circle with a blue outline and a radius of 40 pixels, centered at the point (100, 200). If you see whatsoever trouble with the graphics package, delight call a lab instructor.
-
Lets read and endeavor to empathise this lawmaking, using the below notes.
The statement
window = GraphWin("Circles", 800, 800)creates a window object, stored inside the variable
window. The window's title is Circles. Its width and peak are each 800 pixels (the first number is the width and the second one is the height).To create a circumvolve, we need to first create a Point object that acts as its center. The variable
centerholds this Point object. Notice that the data types of graphics objects brainstorm with upper-case letters, and we are using lowercase letters for the names of variables that hold these objects.Nosotros also made the radius a variable, so that we tin hands alter it later if necessary.
Now, our lawmaking is:
center = Point(100, 200) radius = 40 circumvolve = Circumvolve(middle, radius) # create a circumvolve centered at "center" with radius "radius"
and we could simply this, by re-writing as the equivalent code:
circle = Circle(Point(100, 200), forty) # create a circle centered at (100, 200) with radius xl
For now, either choice is fine.
Subsequently we create and configure our circle, nosotros use the following statement to draw it into the window that we created earlier:
circle.describe(window) # draw the circle in the "window" that nosotros created before
Without that statement, the circle will non appear in the window.
Before our plan finishes, we need to shut the window that nosotros have created. We use the following statement for that purpose.
window.close() # shut the window after the mouse is clicked in the window.
However, if we put this right after the
circle.draw(win), our program will draw the circumvolve and then immediately close the window, earlier you get a chance to run into what has been drawn in it. To foreclose that, we add the following argument:window.getMouse() # wait for the mouse to be clicked in the window window.close() # close the window after the mouse is clicked in the window
The statementwindow.getMouse()forces the program to wait for the user to click the mouse in the window before it proceeds. With this argument, we tin can make sure that the objects that we intended to depict appear in the window before it closes.Answer Question 17 in Moodle. Remember that the graphics coordinates work like this:
- Once y'all are comfortable with these concepts, add a few more circles to this program. Give them dissimilar radii and colors, and identify them in different points in the window. Pay detail attention to how the coordinates of the eye touch the placement of the circles. This page has a listing of colors you tin utilise.
- Once you take drawn at to the lowest degree v circles, continue to Part C.
Role C: Draw a stack of circles
Instructions
- In PyCharm, create a new Python file lab02c.py. Copy-paste the post-obit program into the new window, substituting your proper noun for the italicized text:
""" Program: CS 115 Lab 2c Author: Your name Description: Using the graphics package, this plan will draw a number of circles. """ from graphics import * def master(): window = GraphWin("Circles", 800, 800) # Circumvolve 1 radius = fifty x = 100 y = 100 center = Point(ten, y) circle = Circle(middle, radius) circle.setOutline('bluish') circle.depict(window) # Circle 2 radius = 50 x = 100 y = 100 eye = Indicate(x, y) circle = Circle(centre, radius) circle.setOutline('bluish') circle.depict(window) # Circle three radius = 50 x = 100 y = 100 centre = Point(x, y) circumvolve = Circle(center, radius) circumvolve.setOutline('blueish') circle.draw(window) # Circle four radius = 50 x = 100 y = 100 centre = Point(x, y) circle = Circle(center, radius) circle.setOutline('blue') circle.describe(window) # Circle five radius = 50 10 = 100 y = 100 centre = Point(x, y) circle = Circle(center, radius) circle.setOutline('blue') circle.draw(window) window.getMouse() # wait for the mouse to exist clicked in the window. window.close() # close the window after the mouse is clicked in the window. master() - Run the program. You should see only one circumvolve, since the 5 circles are drawn on top of each other. Click in the window to go out the program.
- Your eventual goal is to modify the circles until you get the following stack:
If you call up you know how, reply Question 18 in your writeup and give it a shot! Y'all tin skip to Part D once yous have it. Otherwise, continue. - Alter the heart of the 2nd circumvolve so that information technology is immediately below, and adjacent to, the beginning circle. Change its color to red so that you tin tell which is which.
- Pay close attention to the new y-coordinate and how it relates to the y-coordinates and radii of the other circles. Respond Question 18 in your writeup.
- Once your answer to Question xviii is correct, change the remaining circles to draw the total stack.
- One time yous take the stack of circles, continue to Office D.
Part D: Draw a stack of circles using a for-loop
In this part, you will start with a new program and use a for-loop to generate the same image as the i that you just finished.
Then, instead of always drawing 5 circles, you will ask the user for the number of circles to draw.
Instructions
- Copy and paste the following programme in the online Python 3 tutor and run it.
ten = 100 y = 100 num_circles = 5 radius = 50 for i in range(num_circles): print('10 =', x, 'and y =', y) # TODO: change the value of y for the next circle and impress it - Run this plan, and reply Questions nineteen–21 in your Moodle writeup.
- Using what yous learned in Questions fifteen–17, supervene upon the TODO comment with an appropriate statement that modifies the value of
yso that your loop prints the y-coordinates you identified in Question xviii. - Test your code in the Python tutor, and brand sure that it prints the verbal values from Question 18.
- In PyCharm, create a new Python file lab02d.py. Copy-paste the following program into the new window, substituting your name for the italicized text:
""" Programme: CS 115 Lab 2 Part D Writer: Your name Description: Using the graphics parcel, this program volition draw a number of circles using a for-loop. """ from graphics import * def main(): window = GraphWin("Circles", 800, 800) x = 100 y = 100 num_circles = 5 radius = l for i in range(num_circles): print('ten =', ten, 'and y =', y) # TODO: copy and paste a code-segment that draws one circle # (from your previous programme, lab02c.py) hither. # TODO: copy the line that modifies the y-value for the next circumvolve # (from the previous footstep) here window.getMouse() window.close() main() - Where indicated by the comment, add the line of code that y'all merely wrote in the Python tutor.
- Run the program. Make certain that its output in the console (text) window is still the aforementioned as that of the Python Tutor. It will also popular upward an empty graphics window.
-
Simply above the line you added, replace the other annotate with code to draw i circle, based on your lawmaking from Function C.
Hints:
- Don't copy the code that sets the radius or the x- and y-coordinates.
- The circles can all exist the same color.
- You should be sure this code is indented inside the loop, so that it runs 5 times and draws 5 circles.
- Run your program and verify that it draws 5 stacked circles, just like in Function C.
- Replace the line
num_circles = five
with a line that gets the value ofnum_circlesfrom the user. Yous can assume that the user volition ever enter a positive integer that is pocket-size enough to fit the circles on the screen. - Exam your programme, and verify that the stack of circles matches the number specified by the user.
- Supervene upon the line
radius = 50
with a line that gets the value ofradiusfrom the user. You can assume that the user always enters a reasonable positive integer. - Modify your calculations then that the circles are stacked right on summit of each other. Yous don't have to change the initial value of
y, but you practice have to change the style it is adapted within the loop. - Test your code with several different numbers of circles and radii. This part of the lab isn't a graded demo, but you lot should feel gratuitous to get a fellow member of the grade staff to test it – you'll build on it in Part Eastward.
- Once you're confident in your Part D code, go on to Function East.
Office E: Draw a square of circles
For the last part of the lab, yous will write a Python plan that accepts user input to generate images that are similar to the one beneath. The user will specify the number of circles on each side of the square shape and the radius of each circle. This image was generated for xi circles and a radius of fifty.
Instructions
- In PyCharm, create a new Python file lab02e.py:
""" Program: CS 115 Lab two Part E Writer: Your name Clarification: Using the graphics parcel, this program will draw a foursquare of circles. """ from graphics import * def main(): window = GraphWin("Circles", 800, 800) # TODO Step i. # Get the number of circles and the radius from the user. # TODO Step ii. # Draw the left vertical circles. # Re-create and paste what you need from your lab02d.py here. # TODO Step 3. # Draw the top horizontal circles. # Re-create and paste the previous code-segment that draws vertical # circles (step 2 in a higher place) and make the necessary changes to it so # that it draws the top row of circles. # It is okay to draw a circle on the existing top circle. # Hint: To draw horizontal circles, think which # coordinate (ten or y) needs to be changed inside the for-loop # TODO Step 4. # Draw the bottom horizontal circles. # Copy and paste the previous code-segment that draws the # tiptop circles (step 3 above) and make the necessary changes # to it then that it draws the bottom row of circles. # It is okay to draw a circle on the existing bottom circle. # TODO Stride 5. # Draw the right vertical circles. # Copy and paste the code-segment that draws the (left) vertically # stacked circles (step ii higher up) and make the necessary changes # to information technology so that information technology draws the right vertical circles. # It is okay to redraw the right-virtually two horizontal circles. # TODO Step 6. # Depict the peak-left-to-lesser-right diagonal circles. # Copy and paste the lawmaking-segment that draws the (left) vertical, # stacked circles (step 2 higher up) and make the necessary changes # to it so that information technology draws the circles that are the left-to-right # diagonal of the foursquare. The modify in successive x and y of # these circles is exactly the same as those in the successive # horizontal and vertical circles, respectively. # Hint: To draw diagonal circles, you would need to modify both # the 10 and y-coordinate inside the for-loop # TODO Footstep seven. # Draw the top-correct-to-bottom-left diagonal circles. # Copy and paste the code-segment that draws the left-to-correct # diagonal circles (stride 6 above) and make the necessary changes # to it then that it draws the circumvolve on the right-to-left diagonal # of the square. # Hint: To draw these circles, think near if the successive x and # y-coordinates inside the for-loop need to increase or subtract. window.getMouse() window.close() main() - Salvage this program as lab02e.py.
- Straight after the TODO Stride 1 comments, write the two lines yous used to inquire the user for the number of circles and the radii of the circles.
- Run the program, and make sure that it asks the user for the two values in the console (text) window. Information technology volition likewise pop upwardly an empty graphics window. Answer the questions so click in the window to exit the plan.
-
Next, you will make the changes specified in TODO Steps 2–7. Hither is a pictorial overview of these steps:
Although you could do this in a few different means, your code will be easier to manage if you write a divide for-loop for each step. The residue of these instructions will walk you lot through each of these TODO steps. After you complete each step, run your code to be certain information technology works (don't try to piece of work on multiple steps at once). To make your life easier, apply a special circle color for the step you are working on, to brand those circles easier to see.
- Direct afterward the TODO Step ii comments, draw a stack of circles down the left edge of the graphics window based on the user's input. Cull initial values for ten and y then that the top circle is 5 pixels away from the height and left edges of the window. Yous should be able to reuse some code from Part D.
- Straight after the TODO Step 3 comments (that is, below all of your copy-pasted code from Pace 2, and outside of its for-loop), draw a row of horizontal circles beyond the elevation, 5 pixels abroad from the top of the screen. Y'all tin can showtime by making a copy of the code you used in Footstep two and figuring out what to modify. Information technology is OK if you describe a circle on top of the existing, acme-left circle.
- Straight later the TODO Step 4 comments, draw a row of circles across the lesser. The leftmost circumvolve in this row should line up with the bottom-left circumvolve you lot drew in Step ii. Once again, information technology'south OK to depict a circle on top of the existing bottom-left circle.
- Straight after the TODO Step five comments, draw a row of circles down the right edge. The summit circle in this column should line upwardly with the top-correct circle you lot drew in Step 3.
- Directly under the TODO Step half dozen comments, draw the left-to-right diagonal. Notice that yous will have to alter both the x and y coordinates each time you go through the loop. Unlike the horizontal and vertical circles, the diagonal circles won't necessarily touch at their edges. That is OK, equally long as they are every bit spaced.
- Finally, after the TODO Step vii comments, draw the right-to-left diagonal straight.
- Make certain the horizontal and vertical circles are red and the diagonal circles are bluish, just like in the picture above.
-
Examination your code with several different numbers of circles and radii. If the user enters an fifty-fifty number of circles, the heart of the square volition expect a piffling bit different, and that's OK. Hither is an example with radius 50 and 10 circles per side:
If yous can match these examples, adjust the window size to (900, 900) and re-try these examples and check the pictures are still fatigued correctly. When you are done testing your lawmaking, suit the window size back to (800, 800) and go to the side by side stride.
- Demo. Call an teacher to demo your Part E code.
- Make sure that your name is in the docstring and that the docstring accurately describes what your plan does.
- Go on to the side by side part.
Consignment Submission
Instructions
- Answer the last question in your Moodle writeup. Review your answers, and and so click the "Adjacent" button at the bottom of the quiz. Once you exercise that, you should see a "Summary of Effort" screen.
-
Click the "Submit all and finish" button. Alarm: Yous must hit "Submit all and terminate" and then that your writeup tin can exist graded! It is not submitted until you do this. In one case you have submitted your quiz, you lot should come across something similar to this at the top of your Moodle window. The important role is that the State shows up as Finished.
Please exit this tab open up in your browser. -
Click on the "Lab 2 lawmaking" link in Moodle and open up in a new tab. Follow the instructions to upload your source lawmaking (lab02e.py) for Lab02. You could either browse for your lawmaking or, using a finder window, drag and drib your lab02e.py from your cs115/Lab02 folder to Moodle. You lot should subsequently see a dialog box which indicates 'Submission Status' every bit 'Submitted for grading'.
- With these confirmation pages open in your browser, you lot may call an teacher over to verify that y'all have completed every part of the lab. Otherwise, you are done!
Source: https://blue.cs.sonoma.edu/cs115/S18/labs/lab02/cs115_lab02.html
0 Response to "Draw a Circle at User Click Python"
Post a Comment