Running a Python Program. I’m guessing you’ve got a computer near your face at the moment? If so, you’ve nearly got everything you need to start writing. Getting Started with Python Programming for Windows Users. Running Your First Program. Getting Started with Python Programming for Mac Users.While Statements — Hands- on Python Tutorial for Python 3. In any case the for loop has required the. This is often too restrictive. A Python. while loop behaves quite similarly to common English usage. If. I say. While your tea is too hot, add a chip of ice. Presumably you would test your tea. If it were too hot, you would. Program CodeBug with Python 3. Python Tutorial: Running Python Programs. Toggle navigation BogoToBogo. Familiarize yourself with the Python shell and IDLE text editor by running through the two sections below. The IDLE Text Editor and Your First Python Program. If you test again and it is still too hot, you. As long as you tested and found it was true. You want it at 1. A. chip of ice turns out to lower the temperature one degree each. You test the temperature each time, and also print out the. In Python you could. The tea is cool enough.')I added a final line after the while loop to remind you that. If you play computer and follow the path of execution, you could. Remember, that each time you reach. Linetemperature. Comment. Each time the end of the indented loop body is reached, execution. When the. test is finally false, execution jumps past the indented body of. A while loop generally follows the pattern of the successive. Condition: do main action to be repeatedprepare variables for the next time through the loop. Test yourself: Following the code. In. English you could mean to stop as soon as the condition you want. In Python the test is only made when. Predict what will happen with this slight variation on the. Follow it. carefully, one step at a time. While. pywhile(i< 9): i=i+2print(i)Check yourself by running the example program test. While. 2. py. The sequence order is important. The variable i is increased before. Another common. error is to assume that 1. Once the body of the loop is started, it. Linei. Comment. 14 2 4 < 9 is true, do loop. No test here. 4 print 1. Predict what happens in this related little program: nums=list()i=4while(i< 9): nums. Check yourself by running the example program test. While. 3. py. 3. 3. The Most General range Function. As in the simpler. To see the entire sequence at once, convert the. The third parameter for the range function is the step size. Each element after the first in the list is. Predict and try in the Shell: Actually the range function is even more sophisticated than. The step size can be negative. Test it. in the Shell. These ranges, like the simpler ranges that we used earlier. Blastoff!')3. 3. 3. Interactive while Loops. Obviously they could have been rewritten with range. Now lets try a more interesting example. Suppose. you want to let a user enter a sequence of lines of text, and want. This could easily be done with a. For. example, in read. Lines. 0. py, the user is prompted for the exact. How many lines do you want to enter? This means the number of repetitions would not be. A while loop is appropriate here. There is. still the question of how to test whether the user wants to. An obvious but verbose way to do this is to ask before. Lines. 1. py. Read it and then run it: lines=list()test. Answer=input('Press y if you want to enter more lines: ')whiletest. Answer=='y': line=input('Next line: ')lines. Answer=input('Press y if you want to enter more lines: ')print('Your lines were: ')forlineinlines: print(line)See the two statements setting test. Answer. one before the while loop and one at the bottom of the loop body. Note. The data must be initialized before the loop, in order for the. Also the test must work. This means the. data for the test must also be set up a second time, in the loop. Two lines must be entered for every one you. A practical alternative is to use a sentinel: a. You could. agree to use the line DONE! Even simpler: if you assume all the. Since the sentinel is an. You need. the opposite condition. To negate a condition in Python, you may. English,Of course in this situation there is a shorter way,Run the example program read. Lines. 2. py, shown below: lines=list()print('Enter lines of text.')print('Enter an empty line to quit.')line=input('Next line: ')# initalize before the loopwhileline!='': # while NOT the termination conditionlines. Next line: ')# !! Hence you see the. It is easy to forget the second place. After reading the rest of this paragraph. It will never stop! The. variable line will forever have the initial value you gave it! That means. hold the Ctrl key and press c. Note. As you finish coding a while loop, it is good practice to. Did I make a change to the variables, inside. False? The earliest while loop examples had numerical tests and the code. Interactive Sum Exercise. Only print out the sum after all the. Safe Number Input Exercise. Round displayed amounts. The math: The amount next year is the amount now times. I have $5. 00 now and the interest rate is . I have $5. 00*(1. I have. $5. 20*(1. Strange Sequence Exercise. Graphical Applications. Suppose you want the user to be able to. Polygon by clicking on vertices they choose interactively. A while loop is suggested for such a repetitive. As with entering lines of text interactively, there is the. If you make only a certain region be allowed for the. Polygon, then the sentinel can be a mouse click outside the region. It involves a boundary rectangle and mouse. Graph. Win, and may as well return the Polygon. Read the following start: defpoly. Here(rect,win): ''' Draw a polygon interactively in Rectangle rect, in Graph. Win win. Call it poly. A list of vertices is needed. I need to. append to this list. It must be initialized first. The latest mouse click point is needed. Call it pt. Certainly the overall process will be repetitious, choosing point. Still it may not be at all clear how to make an. Python loop. In challenging situations like this it is. For instance to get up to a triangle (3 vertices in our list and a. Outline('red')rect. Mouse()vertices. append(pt)poly=Polygon(vertices)poly. Mouse()poly. undraw()# missing latest pointvertices. Polygon(vertices)poly. Mouse()poly. undraw()# missing latest pointvertices. Polygon(vertices)poly. Mouse()# assume outside the regionrect. There is a fine point here that I missed the first time. The. vertices of an existing Polygon do not get mutated in this system. A new. Polygon gets created each time with the new vertex list. The old. Polygon does not go away automatically, and extraneous lines appear. I arbitrarily. chose for it to go before the vertices list is changed. The rest. of the order of the lines is pretty well fixed by the basic logic. If you think of the repetitions through a large number of loops. The body of a loop in Python, however, is written as a. We can cut a circular loop anywhere to get a piece. In practice, the place you cut the. Python has one main constraint: The processing in. Python from the end of one time through the loop to the beginning. The continuation condition is. Inside, the loop heading will be. With this condition in mind, look for where to split to loop. It. needs to be after a new pt is clicked (so it can be tested) and. Polygon is created (so it does not include the. In particular, with the sequence above. Exercise Moving Undraw considers. I will proceed with. Python loop after the undraw line. The last time there is no. I could redo the loop moving the undraw. Exercise Moving Undraw below). Instead think how to make it work at the. There are several possible approaches. You want the undraw line. Hence it is a statement you. That suggests an if statement. This is the same as the continuation condition for the loop. You could just. add a condition in front of the last line of the loop: ifis. Inside(pt,rect): poly. I find this option unaesthetic: it means duplicating the. Instead of avoiding the undraw as you exit the loop, another. This only needs to be done once, not. Then the repetitious lines collapse neatly. Compare the steps to the ones. This function is illustrated in the example program. Poly. py. Other than standard graphics example code, the. Rectangle(Point(5,5. Point(2. 00,1. 20))poly. Here(rect. 1,win)poly. Fill('green')rect. Rectangle(Point(2. Point(3. 50,3. 50))poly. Here(rect. 2,win)poly. Outline('orange')As you can see, the returned polygons are used to make color. In earlier animation examples a while loop would also have been. Rather than continuing the animation a fixed number of. Thus far the only way to use the. Mouse(). This is not going to work in an. Mouse(), whereas the animation should continue until the. In full- fledged graphical systems that respond to events, this is. Zelle’s graphics is built on top of a capable. Mouse(). As an example, run example program random. Circles. While. py. Be. sure to follow the prompt saying to click to start and to end. Aside from the prompts, the difference from the previous. Circles. py program is the replacement of the original. Mouse()==None: #NEW*The graphics module remembers the last mouse click, whether or not. Mouse(). A way to. Mouse(). is check. Mouse(). It does not wait for the mouse as in. Mouse(). Instead it returns the remembered mouse click - . Mouse or check. Mouse. In that. case check. Mouse() returns None (the special object used to. The check. Mouse method allows for a loop that does not stop. A similar elaboration can be made for the other examples of. In bounce. While. I modified. bounce. The only slight added modification. In. Box, so I included it. Look at the source code for. While. py, with the few changes marked NEW. In bounce. 2. py I also made a more interesting change to the. Try example. program bounce. The program includes a new utility function to help determine the. This is done by calculating the. Note the. multiple assignment statement to both dx and dy, set from the tuple. User. Shift. This shift would generally be much. Ball are scaled way down by a factor scale. Point(win. get. Width()/2,win. Height()/2)#NEW central starting pointball=make. Disk(center,radius,win)#NEW interactive direction and speed settingprompt=''' Click to indicate the direction andspeed of the ball: The further youclick from the ball, the faster it starts.'''(dx,dy)=get. User. Shift(center,prompt,win)scale=0. In. Box(ball,dx*scale,dy*scale,x. Low,x. High,y. Low,y. High,win)The bounce. In. Box method has the same change to the loop as in. Circles. py example. The method then requires the.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
December 2016
Categories |