Conditionals and loops — Beginning Python Programming for Aspiring Web Developers. Conditional execution. The simplest form is the if statement, which has the. BOOLEANEXPRESSION: STATEMENTSA few important things to note about if statements: The colon (: ) is significant and required. The header line of the if statement begins with the keyword if. The indented statements that follow are called a block. The first. unindented statement marks the end of the block. The entire block of. False, and. instead all the statements under the else clause are executed. There is no limit on the number of statements that can appear under the two. They mean the same thing, and. Notice too that else is not a statement. One way to express a computation like that is a chained. STATEMENTS. Again, exactly one branch will be. There is no limit of the number of elif statements but only a. If the first is false, the next is checked. If one of them is true, the corresponding branch executes, and the. Even if more than one condition is true, only the first true. Those two branches. Although the indentation of the statements makes the structure apparent, nested. For example, we can rewrite the following code using a single. Repeating identical or. Repeated execution of a set of statements is called iteration. A new assignment. The output of this program isbecause the first time bruce is printed, its value is 5, and the second. Here is what reassignment looks like in a state snapshot: With reassignment it is especially important to distinguish between an. For. example, if a==7 then 7==a. But in Python, the statement a=7. Furthermore, in mathematics, a statement of equality is always true. In Python, an assignment statement. The third line changes the value of a but does not change the value of. Note. In some programming languages, a different symbol is used for assignment. Otherwise the. loop will repeat forever, which is called an infinite loop. I should also point out that the second time that the program's execution reaches the 'break' statement in the. How does one break the execution of a long-running process in the python console of ArcMap? For example, how do you break a long iteration like the one below once it. Visualize Execution Live Programming Mode (NEW!) Break, continue, pass, and the Loop else Now that we’ve seen a few Python loops in action, it’s time to take a look at two simple statements that. While Python includes many. In the case of the “Guess the Number” program. A break statement tells the execution to jump immediately out of the while-block. Home; Python 2 Tutorial; Python 3 Tutorial. Execution of a Python program means execution of the byte code on the Python Virtual Machine (PVM). How to break out of multiple loops in Python? Why doesn't Python just have 'break(n). An endless source of amusement for computer programmers is the observation that. In the case here, we can prove that the loop terminates because we know that. In other cases, it is not so easy to tell. What you will notice here is that the while loop is more work for you —. Choosing between for and while? Tracing involves “becoming the. To understand this process, let’s trace the execution of the program from. The while statement section. At the start of the trace, we have a local variable, name with an initial. Harrison'. Our trace so far would look something like this: name guess pos output- -- - - -- -- - -- - -- -- -'Harrison' 'Maribel' 0. Since guess!=nameandpos< len(name) evaluates to True. The user will now see. Nope, that's not it! Hint: letter 1 is 'H'. Guess again: Assuming the user enters Karen this time, pos will be incremented. True, and our. trace will now look like this: name guess pos output- -- - - -- -- - -- - -- -- -'Harrison' 'Maribel' 0 Nope, that's not it! Hint: letter 1 is 'H'. Guess again: 'Harrison' 'Henry' 1 Nope, that's not it! Hint: letter 2 is 'a'. Guess again: A full trace of the program might produce something like this: name guess pos output- -- - - -- -- - -- - -- -- -'Harrison' 'Maribel' 0 Nope, that's not it! Hint: letter 1 is 'H'. Guess again: 'Harrison' 'Henry' 1 Nope, that's not it! Hint: letter 2 is 'a'. Guess again: 'Harrison' 'Hakeem' 2 Nope, that's not it! Hint: letter 3 is 'r'. Guess again: 'Harrison' 'Harold' 3 Nope, that's not it! Hint: letter 4 is 'r'. Guess again: 'Harrison' 'Harry' 4 Nope, that's not it! Hint: letter 5 is 'i'. Guess again: 'Harrison' 'Harrison' 5 Great, you got it in 6 guesses! Tracing can be a bit tedious and error prone (that’s why we get computers to do. From a trace we can learn a lot about the way our code works. Abbreviated assignment. We pronouce the. operator as “plus- equals”. Another while example. The continue statement. Nested Loops for Nested Data. This needs a. counter, and for each student we need a second loop that tests each of the. Count how many students are taking Comp. Scicounter=0for(name,subjects)instudents: forsinsubjects: # a nested loop! In. Python chained conditionals are written with if.. A Python statement that has two parts: a header and a body. In Python the keywords if, elif, and else are. A variable used to count something, usually initialized to zero and. An invisible marker that keeps track of where the next character will. Decrease by 1. definite iteration. A loop where we have an upper bound on the number of times the. Thus when you can. To follow the flow of execution of a program by hand, recording the. Chapter 4. Topics Covered In This Chapter. The computer will tell you if each guess is too high or too low. You win if. you can guess the number within six tries. This is a good game to code because it uses random numbers. You’ll learn how to convert. Since this. program is a game, we’ll call the user the player. The. text that the player types in is in bold. Hello! What is your name? Albert. Well, Albert, I am thinking of a number between 1. Take a guess. 1. 0Your guess is too high. Take a guess. 2. Your guess is too low. Take a guess. 4. Good job, Albert! You guessed my number in 3. Open a new file editor window by clicking on the File. In the blank window that appears, type in. Then run the program by. F5. When you enter this code into the file editor, be. Some. lines have four or eight spaces of indentation. IMPORTANT NOTE! The programs in this. Python 3, not Python 2. When the IDLE window starts, it. Python 3. 4. 2” at the top. If you have Python 2. Python 3 installed at the same time. To download Python. If you get errors after typing this code in, compare the code you. What is your name?') 7. You guessed my number in ' + guesses. Taken + '. guesses!')3. The number I was thinking of was ' + number)The first line is a comment. Remember that Python will ignore. This just reminds us what this program does. The second line is an import statement. You’ve already seen statements. While Python includes many built- in functions, some functions. You. can use these functions by importing their modules into your program with an import. Line 2 imports the module named random so that the program. You’ll. store the number of guesses the player has made in this variable. Since the player. What is your name?')7. Programmers often reuse code from their. Line 6 is a function call to the print() function. When your. program calls a function, it runs this mini- program. The code inside the print(). Line 7 lets the user type in their name and stores it in the my. Name. just whatever string the player typed. Computers are dumb and just follow their. Function. 9. Remember, function calls can be part of expressions. The randint() function is provided by the random module, so you. Line 9 passes 1. between the parentheses separated by commas that follow the function name. The. random integer that randint() returns is stored in a variable named. Just for a moment, go back to the interactive shell and enter import random. Then enter random. It will return an integer between 1. You’ll use randomness in many games. For example, enter random. Or try random. randint(1. For example, enter the following into the interactive shell. The. results you get when you call the random. You can change the game’s code slightly to make the game behave. Try changing line 9 and 1. The plus signs concatenate the three. And that one string is the argument. If you look closely, you’ll see that the. Loops let you execute code over and over. However, you need to learn a few other concepts first before learning. Those concepts are blocks, Booleans, comparison operators. Several lines of code can be grouped together in a block. Every. line in a block of code has the same minimum. You can tell where a block begins and ends by looking at. This is the line’s indentation. A block begins when a line’s indentation increases (usually by. Any following line also indented by four spaces is part of the. The block ends when there’s a line of code with the same indentation. This means blocks can exist within other blocks. Line 1. 3 has an indentation of four spaces. Since this indentation is. This. block is labeled (1) in Figure 4- 1. This block will continue until a line with. Blank lines are. ignored. Line 2. 0 has an indentation of eight spaces. Eight spaces is more. This block is labeled (2) in Figure. This block is inside of another block. Figure 4- 1: Blocks and their indentation. The black dots. represent spaces. Line 2. 2 has only four spaces. Because the indentation has. Line 2. 0 is the only line in that. Line 2. 2 is in the same block as the other lines with four spaces. Line 2. 3 increases the indentation to eight spaces, so again a new. It is labeled (3) in Figure 4- 1. To recap, line 1. Lines 1. 3 to 2. 3 all in one. Line 2. 0 is in a block in a block marked as (2). Line 2. 3 is. the only line in another block in a block marked as (3). The Boolean data type has only two values: True or False. The rest of the value’s. You will use Boolean values (called bools for short) with comparison operators to form. Every value in Python belongs to one data type. Line 1. 2 has a while statement: 1. The < sign is a comparisonoperator. Comparison operators compare two values and evaluate to a True. Boolean value. A list of all the comparison operators is in Table 4- 1. Table 4- 1: Comparison operators. Operator Sign. Operator Name< Less than> Greater than< =Less than or equal to> =Greater than or equal to==Equal to!=Not equal to. You’ve already read about the +, - , *, and / math operators. Like. any operator, the comparison operators combine with values to form expressions. Taken. < 6. A condition is an expression that. Boolean value. A condition is just another name for an. True or False. Conditions are. For example, the condition guesses. Taken < 6. asks, “is the value stored in guesses. Taken less than the number 6?”. If so, then the condition evaluates to True. If not, the. condition evaluates to False. In the case of the “Guess the Number” program, on line 4 you. Taken. Because 0 is less than 6. Boolean value of True. The evaluation. would look like this: guesses. Taken <. 6 . But because 6. isn’t less than 0, the condition 6 < 0 evaluates to False. True. Notice that 1. False because the number. They are the same size. If Alice were the. Bob, you wouldn't say that Alice is taller than Bob or that. Alice is shorter than Bob. Both of those statements would be false. Now try entering these expressions into the interactive shell: > > > 1. True> > > 1. False> > > 1. False> > > 1. False> > > 1. True> > >. Hello' == 'Hello'True> > >. Hello' == 'Goodbye'False> > >. Hello' == 'HELLO'False> > >. Goodbye' != 'Hello'True= and ==Try not to confuse the assignment operator (=) and the “equal to”. The equal sign (=) is used in assignment. It’s easy to. accidentally use one when you meant to use the other. Just remember that the “equal to” comparison operator (==). String and integer values will never be equal to each other. For. example, try entering the following into the interactive shell: > > > 4. Hello'False> > > 4. Truewhile statements. The while statement marks the beginning of a loop. Loops can. execute the same code repeatedly. When the execution reaches a while. If the. condition evaluates to True, the execution moves inside the following. In Guess the Number, the first line after the while- block. A while statement always has a : colon after the. Statements that end with a colon expect a new block on the next. If the condition evaluates to True (which it does the. Taken is 0), execution will enter. Once the program reaches the. As before, if the condition is True the execution. Each time the execution goes through the loop is. This is how the loop works. As long as the condition is True. False. Think of the while statement as. The Player Guesses. That number is stored in a variable named guess. Functions. 15. The int(). Passing 'forty- two' to int(). The string you pass to int() must be made up of. Traceback (most. recent call last): File. It evaluates to the integer value 5: Remember, the input() function always returns a. If the player types 5. Line 1. 6 overwrites the string value in guess. This lets the code later in the. One last thing: Calling int(guess) doesn’t. The code int(guess) is an. What changes guess is the assignment statement: guess = int(guess)The float(), str(), and bool() functions will. Boolean versions of the arguments passed to. Try entering the following into the interactive shell: > > >. False)'False'> > >. False> > >. True. Using the int(), float(), str(). Incrementing Variables. Taken. Think of line 1. Taken variable should be one more than what it. Adding one to a variable’s integer or float value is called incrementing the variable. Subtracting one from a. The execution will run the code. True. If. the condition is False, then the code in the if- block is skipped. Using if. statements, you can make the program only run certain code when you want it to. Line 1. 9 checks if the player’s guess is less than the computer’s. If so, then the execution moves inside the if- block on line 2. The if statement works almost the same as a while. But unlike the while- block, the execution doesn’t jump back to. It just continues down to the next line. See Figure 4- 3 for a comparison. Figure 4- 3: if and while statements. If this condition is True, then the print() function call. If it is, the program runs the break statement on line. A break statement tells the. The break statement doesn’t bother rechecking. The break statement is only found inside loops, such as in a. If the player’s guess isn’t equal to the secret number, the. This means the execution will. Taken < 6). The execution left the. False. (when the player runs out of guesses) or the break statement on line. Line 2. 8 checks to see if the player guessed correctly. If so, the. execution enters the if- block at line 2. You guessed my number in ' + guesses. Taken + '. guesses!')Lines 2. True (that is, if the player correctly guessed. Line 2. 9 calls the str() function, which returns the string. Taken. Only string values can concatenate to other strings. This. is why line 2. Taken to the string form. Otherwise. trying to concatenate a string to an integer would cause Python to display an. Check if the Player Lost. If this. condition evaluates to True, the execution moves into the if- block on. Lines 3. 3 and 3. True. 3. 3. This requires concatenating strings. Line 3. 3 will overwrite number with a string. Nope. The number I was thinking of.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
January 2017
Categories |