{"id":125,"date":"2021-06-28T19:59:28","date_gmt":"2021-06-28T19:59:28","guid":{"rendered":"http:\/\/juthon.com\/?p=125"},"modified":"2021-06-29T12:29:12","modified_gmt":"2021-06-29T12:29:12","slug":"passage-5-python-loops","status":"publish","type":"post","link":"http:\/\/juthon.com\/index.php\/2021\/06\/28\/passage-5-python-loops\/","title":{"rendered":"Passage 5: Python Loops"},"content":{"rendered":"\n<p><em>We code in Python<\/em><\/p>\n\n\n\n<p>Hello! How are you. Today's passage is devoted to loops. We'll start with the <em>while loop<\/em>. In&nbsp;programming, loops are used to repeat the same instruction multiple times. We would not be exaggerating when we say that loops are one of the most important elements of programming.<\/p>\n\n\n\n<p>What are we going to start from? Maybe a little warm-up? Let's write a short applet that will convert the temperature in Celsius degrees  to the temperature in kelvins. As you probably remember from physics lessons, the Kelvin scale is shifted 273 units up from the Celsius scale. So 0\u00b0 C is 273 K, 10 \u00b0 C is 283 K etc. Here is our&nbsp;code:<\/p>\n\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">a = int (input ('Enter the temperature in Celsius degrees:'))<br>b = a + 273<br>print ('You entered the temperature ', a, '\u00b0C', sep = '')<br>print ('In kelvins this temperature is:',&nbsp;b)<br><\/p>\n\n\n<p>The program is simple, the syntax of all commands is known to us from previous passages of the series<a href=\"#_ftn1\">[1]<\/a>.<\/p>\n\n\n\n<p>In the same physics lessons, you should also remember that the temperature of matter cannot be lower than 0 K (absolute zero). This is the temperature corresponding to \u2011273\u00b0 C. We will improve our code by adding a conditional instruction that responds with the message \"Incorrect value\" to the user entering a temperature lower than \u2011273\u00b0&nbsp;C<\/p>\n\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">a = int (input ('Enter the temperature in Celsius degrees:'))<br>if a &lt;-273:<br>&nbsp;&nbsp;&nbsp; print ('Invalid value')<br>else:<br>&nbsp;&nbsp;&nbsp; b = a + 273<br>&nbsp;&nbsp;&nbsp; print ('You entered the temperature', a, '\u00b0 C', sep = '')<br>&nbsp;&nbsp;&nbsp; print ('In kelvins this temperature is:',&nbsp;b)<br><br><\/p>\n\n\n<p>Run the above script. Works flawlessly. And yet\u2026 We can't quite be satisfied, can we? When the user enters an incorrect temperature value, the program will scold him and exit. Is this really how a decent program is supposed to work? Of course not. The program is not allowed to shut down after the user gives the wrong answer, but it should ask the user again and again for the correct answer. Until the proper reaction!<\/p>\n\n\n<h2 class=\"fonts-plugin-block \" style=\"font-weight: normal\">We get to know the&nbsp;loops<\/h2>\n\n\n<p>The described situation is the bread and butter of programming. We need the program to repeat an action many times. We will achieve this by using&nbsp;loops.<\/p>\n\n\n\n<p>The while loop (\"do something while \u2026\") is very similar in its construction to the if conditional, with the difference that as after <em>if<\/em> keyword Python would execute the given statements once, after the <em>while<\/em> keyword Python would execute them \u2014 as they say \u2014 \"in circle \"until the condition is no longer met.<\/p>\n\n\n\n<p>In our example, the condition is: giving an \"incorrect\" temperature by the user. If the user persists and enters incorrect temperatures again and again, the program will stubbornly inform him that he is making a mistake and ask for the temperature again. The \"game\" will continue until the user finally enters a temperature higher than \u2011273\u00b0&nbsp;C.<\/p>\n\n\n\n<p>Let's write the appropriate code.<\/p>\n\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">a = int (input ('Enter the temperature in Celsius degrees:'))<br>while a&lt;-273:<br>&nbsp;&nbsp;&nbsp; print ('Invalid value')<br>&nbsp;&nbsp;&nbsp; a = int(input('Enter the temperature in Celsius degrees:'))<br>else:<br>&nbsp;&nbsp;&nbsp; b = a+273<br>&nbsp;&nbsp;&nbsp; print ('You entered the temperature', a, '\u00b0C', sep = '')<br>&nbsp;&nbsp;&nbsp; print ('In kelvins this temperature is:',&nbsp;b)<br><br><\/p>\n\n\n<p>The script is not much different than the previous one, based on <em>if-conditional-instruction<\/em>. It was enough to replace the word \"if\" with the word \"while\" \u2014 one might say. Almost. In addition to this change, we had to \u2014 inside the while loop \u2014 repeat the first line of code, the one with the input command. Why? It is quite obvious. To have Python repeat the execution of this line of code multiple times. The statements used after the word while \u2014 and indented by four spaces \u2014 are the body of the loop and are repeatedly executed.<\/p>\n\n\n<h2 class=\"fonts-plugin-block \" style=\"font-weight: normal\">While loop construction<\/h2>\n\n\n<p>A while loop consists of two parts: the condition and the loop body. The body of the loop is a set (sequence) of commands. The loop executes the sequence of commands multiple times until the given condition becomes false.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" src=\"http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_00_pass_05.jpg\" alt class=\"wp-image-128\" width=\"856\" height=\"198\" srcset=\"http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_00_pass_05.jpg 656w, http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_00_pass_05-300x70.jpg 300w\" sizes=\"(max-width: 856px) 100vw, 856px\"><\/figure>\n\n\n\n<p>Additionally (as can be seen in the diagram above) there is an alternative part that starts with the else. This alternative part \u2014 in the case of the while loop \u2013 shows a little trouble, but more on that in a moment. The while loop is executed (potentially) an infinite number of times as long as Python determines that the given condition is True. When the condition becomes False, the loop ends its work (the&nbsp;programme \"exits\" the&nbsp;loop).<\/p>\n\n\n\n<p>The commands specified after the <em>else<\/em> are executed once when exiting the&nbsp;loop.<\/p>\n\n\n\n<p>The variable referenced by the while loop must first be defined in the program (before opening the loop) so that it can be reused inside the loop later. Hence \u2014 in our example, the line a = int (input ('Enter temperature in degrees Celsius:')) appears twice. First in front of the loop, then inside it. We will come back to this&nbsp;issue&nbsp;\u2026<\/p>\n\n\n<h2 class=\"fonts-plugin-block \" style=\"font-weight: normal\">An example of using the while&nbsp;loop<\/h2>\n\n\n<p>Let's illustrate a while loop with the simplest possible example, shorter and perhaps easier than our previous example converting from Celsius to Kelvin.<\/p>\n\n\n\n<p>This example prints the value of the variable<em> <\/em>i, which is initially zero, and increments by 1 each time the loop is run. The loop runs as long as i is less than&nbsp;5<\/p>\n\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">i = 0<br>while i &lt;5:<br>&nbsp;&nbsp;&nbsp; print ('number:', i)<br>&nbsp;&nbsp;&nbsp; i = i + 1<br><br>Output:<br>number: 0<br>number: 1<br>number: 2<br>number: 3<br>number: 4<br><\/p>\n\n\n<p>From this example it is clear that the loop \u2014 in its first cycle \u2014 refers to the value of the variable given before the loop (i = 0) and then reaches for the updated values (after each loop) with the code line i = i + 1,    i.e. \u2014 otherwise speaking \u2013 the values increased by 1 for each circuit. This is the idea behind the while loop: check the initial value in the code before the loop; then update this value and check again. The loop continues to generate <em>print<\/em> until the value of i &lt;5. Therefore, output (understood as a printout on the screen) covers the numbers from 0 to&nbsp;4.<\/p>\n\n\n\n<p>Note, however, that  within the last cycle of the loop \u2014 after generating the string \"number: 4\" \u2014 &nbsp;the&nbsp;value of the variable is increased once again.  Finally, the variable i has the value 5.<br>If you changed the order of the lines in the code and make your script like&nbsp;this:<\/p>\n\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">i=0<br>while i&lt;5:<br>&nbsp;&nbsp;&nbsp; i=i+1<br>&nbsp;&nbsp;&nbsp; print('number:', i)<br>&nbsp;&nbsp;&nbsp;<br>your loop will generate this &nbsp;output:<br>number: 1<br>number: 2<br>number: 3<br>number: 4<br>number: 5<\/p>\n\n\n<p>The advantage is that the last printed value of the variable is equal to the current value calculated by the program. The disadvantage, however, boils down to the fact that we do not meet the condition: \"print values until they are less than 5\". Which version of the program is better? There is no answer to that. It is important that you write code with careful awareness of the result of running it.<\/p>\n\n\n<h2 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Exiting the&nbsp;loop<\/h2>\n\n\n<p>As we remember, when exiting of the loop (the value of condition = False), Python will execute the block indicated by the word else&nbsp; (the commands following the else keyword and indented by four spaces). Let's extend our program so that \u2014 when we exit the loop \u2014 we print the message \"Good&nbsp;bye!\"<\/p>\n\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\"><br>i=0<br>while i &lt; 5:<br>&nbsp;&nbsp;&nbsp; print('number:', i)<br>&nbsp;&nbsp;&nbsp; i=i+1<br>else:<br>&nbsp;&nbsp;&nbsp; print('Good bye!')<br><br>print('And now the rest of the programme.')<br><br>Output:<br>number: 0<br>number: 1<br>number: 2<br>number: 3<br>number: 4<br>Good bye!<br>And now the rest of the programme.<\/p>\n\n\n<p>The program executes the loop five times, then executes the alternative code (else), and finally proceeds to execute the commands outside the loop \u2014 in the main code (the line \"And now the rest of&nbsp;the programme.\").<\/p>\n\n\n<h3 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Exercise<\/h3>\n\n\n<p>Build a script that converts temperature from Celsius to Kelvin. Add a code to count the number of&nbsp;times the user entered an incorrect temperature value. Write down the command, which prints the&nbsp;message at the end of the script: \"You have entered the wrong temperature i times.\" \u2014 where, of&nbsp;course, in&nbsp;place&nbsp;of the letter \"i\", the actual number of incorrect passes will appear.<\/p>\n\n\n<h3 class=\"fonts-plugin-block \" style=\"font-weight: normal\">The Riddle<\/h3>\n\n\n<p>While browsing (even on the internet) various examples of the use of the while loop in Python, we&nbsp;can find scripts very similar to our script that prints consecutive numbers from 0 to&nbsp;4.<\/p>\n\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">i = 0<br>while i &lt;5:<br>&nbsp;&nbsp;&nbsp; print ('number:', i)<br>&nbsp;&nbsp;&nbsp; i = i + 1<br>print ('Good bye!')<br>print ('And now the rest of the programme.')<\/p>\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">Output:<\/p>\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">number: 0<br>number: 1<br>number: 2<br>number: 3<br>number: 4<br>Good bye!<\/p>\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">And now the rest of the programme.<\/p>\n\n\n<p>Similar but not the same example as before. The code is slightly different from the previous one, right? The else is missing. The command that followed the else \u2014 and was indented by four spaces \u2014 is now in the main code. The output, however, is the same as before.<\/p>\n\n\n\n<p>Since the output is identical with \"else\" and without \"else\", does it mean that \u2014 in the case of a while loop \u2014 the else is redundant? The answer is yes. We don't have to use the else, and we can simply place the commands (we want to execute when exiting the loop) in the main code<a href=\"#_ftn2\">[2]<\/a>.<\/p>\n\n\n\n<p>Let's ask another question: and is the same simplification \u2013 that is, placing alternate statements directly in the main code \u2013 also applicable to the if statement? The answer is: definitely not. But why exactly? After all, while and if seemed so logically similar to each&nbsp;other&nbsp;\u2026<\/p>\n\n\n\n<p>Well, only \"seemed\" \u2013 unfortunately. Let's try to unravel this mystery.<br><\/p>\n\n\n<h3 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Where is the difference<\/h3>\n\n\n<p>At the beginning of our course, we emphasised that learning programming develops your ability to think logically. Time to check it out \"in action\". Showing that the else has a different role for the if statement than for the while statement is great training for \"gray cells\" of our brains.<\/p>\n\n\n\n<p>Let's start by drawing a simple diagram. When Python already executed either a conditional if statement or a while loop, it then proceeds to main code statements.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" src=\"http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_01_pass_05.jpg\" alt class=\"wp-image-130\" width=\"813\" height=\"177\" srcset=\"http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_01_pass_05.jpg 660w, http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_01_pass_05-300x65.jpg 300w\" sizes=\"(max-width: 813px) 100vw, 813px\"><\/figure>\n\n\n\n<p>Execution \u2014 be it a conditional statement or a while loop \u2014 always starts with checking the condition. Python checks to see if, given the current value of a variable, the condition is True or False. We remember this rule, right? The crux of the difference is that in the case of a conditional statement, it is possible to move to subsequent commands in the main code both when the condition is True or False. However, in the case of a loop, the transition to the subsequent commands of the main code is possible only when the condition is False. When the condition is True, Python doesn't reach for any more lines of code. It is spinning in circles (in a loop), that is, it updates the value of the variable and checks whether the condition is True again, and updates again and checks again and again and&nbsp;again.<\/p>\n\n\n\n<p>If the condition were always True, we would loop forever.<\/p>\n\n\n\n<p>Since \u2014 in the case of a while loop \u2014 the transition to subsequent commands of the main code is possible only when the condition is False, the program <strong>must<\/strong> execute the else part of the code (because, by definition, the alternate part of the code is executed when the condition is&nbsp;False).<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" src=\"http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_02_pass_05.jpg\" alt class=\"wp-image-132\" width=\"863\" height=\"362\" srcset=\"http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_02_pass_05.jpg 615w, http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_02_pass_05-300x126.jpg 300w\" sizes=\"(max-width: 863px) 100vw, 863px\"><\/figure>\n\n\n\n<p><strong>In case of the while loop, the program proceeds to \"subsequent lines of the main code\" only&nbsp;if&nbsp;the condition's value becomes False.<\/strong><\/p>\n\n\n\n<p>And what is the consequence of taking the value False by the condition? Then the alternative command is executed (the code fragment after the word&nbsp;else).<\/p>\n\n\n\n<p>What is the lesson from this? In the case of a while loop (unlike the case of the if statement), it&nbsp;is&nbsp;impossible to skip the execution of an alternate command. It is impossible to exit the loop with condition value = True, that is without executing the else part. In programming, the role of the else keyword is&nbsp;to allow the part of code that follows this keyword (and is indented by four spaces) to be <strong>omitted<\/strong>, under a&nbsp;certain condition. Since such omission is not possible, in the case of a while loop the else becomes redundant. The commands we want to execute can be written directly in the main&nbsp;code.<\/p>\n\n\n\n<p>In short, the alternative command is guaranteed to be executed. And since the alternative command will definitely be executed, why write \"else\" in front of it? So let's repeat: using else keyword with a&nbsp;while loop doesn't make much sense. Most programmers omit the else and simply write the set of commands \u2014 to be executed when they exit the loop \u2014 in the main&nbsp;code.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" src=\"http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_03_pass_05.jpg\" alt class=\"wp-image-134\" width=\"821\" height=\"202\" srcset=\"http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_03_pass_05.jpg 631w, http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_03_pass_05-300x74.jpg 300w\" sizes=\"(max-width: 821px) 100vw, 821px\"><\/figure>\n\n\n<h3 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Exercise<\/h3>\n\n\n<p>Write a short program that asks the user the question: 'Do you like candy? y \/ n ' Use the if\u2026 else\u2026 &nbsp;conditional statement, which will differentiate the program's response depending on the typing of the letter y or n by the user. For example, when the user presses y, the program will print the message: 'You like candy', and when the user presses n, the message: 'You don't like candy'. Run program and select y. Restart and select n. Observe the effect.<\/p>\n\n\n\n<p>Then make changes to the script, by removing the else keyword, and placing the <em>alternative command<\/em> in the main code. Run program and select y. Restart and select n. Observe the effect.<\/p>\n\n\n\n<p>Now write a new script that will use a while\u2026 else\u2026 loop, instead of the if\u2026 else\u2026 conditional. Run&nbsp;it and make similar test. Make the same changes as before and test&nbsp;again.<\/p>\n\n\n<h2 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Summary<\/h2>\n\n\n<p>From today's passage, remember:<\/p>\n\n\n\n<ul><li>Python loops are used to execute a piece of code multiple times<\/li><li>an example of a loop is a while loop that runs as long as the specified condition is&nbsp;true<\/li><li>The while loop is similar to the if statement except that while if checks the condition once, while checks the condition multiple times: again and again until it is&nbsp;False.<\/li><\/ul>\n\n\n\n<p>For this reason, this loop will come in handy when you want to force the user to provide a rational answer to a question asked by the program. Although similar to if, the logic of while is different in the alternate code that follows the word&nbsp;else.<\/p>\n\n\n<h2 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Appendix: With or without a&nbsp;space<\/h2>\n\n\n<p>The commad:<\/p>\n\n\n\n<p>print ('You entered the temperature ', a, '\u00b0C',&nbsp;sep&nbsp;=&nbsp;'')<\/p>\n\n\n\n<p>combines three elements:<\/p>\n\n\n\n<ul><li>string: 'You entered the temperature&nbsp;'<\/li><li>variable a (which has a numerical value)<\/li><li>string: '\u00b0C'<\/li><\/ul>\n\n\n\n<p>We connect these elements (as you can see) with commas. Concatenation using the '+' sign would only be possible if all three elements were of type 'text'. When we combine elements of different types (text and numbers), we have no other choice as to use commas.<\/p>\n\n\n\n<p>Python \u2014 when printing \u2014 separates the given elements with a space by default.<\/p>\n\n\n\n<p>Let's take a test. Please type in the&nbsp;shell:<\/p>\n\n\n\n<p>print ('You entered the temperature', 10, '\u00b0C') &nbsp;\u2013 and press&nbsp;Enter.<\/p>\n\n\n\n<p>You should get this effect: &nbsp;You entered the temperature of 10 \u00b0C<\/p>\n\n\n\n<p>If you are a perfectionist, you may not be satisfied with the result, because the symbol for Celsius degrees (\u00b0C) should not be separated by a space from the number 10. It is correctly spelled: 10\u00b0C, not 10 \u00b0C.<\/p>\n\n\n\n<p>How do I get rid of unwanted space? Pretty straightforward. While Python defaults to using a space as the separator in the print statement, it allows the programmer to define a different separator, if the programmer wishes.<\/p>\n\n\n\n<p>This is done by writing sep= and quoting the selected separator in quotation marks, e.g. a dash or a period:<\/p>\n\n\n\n<p>sep = '-' &nbsp;&nbsp;# this defines a dash as a separator<\/p>\n\n\n\n<p>When you don't want any separator, write<\/p>\n\n\n\n<p>sep = '' &nbsp;&nbsp;# open quotation and close quotation with nothing in between<\/p>\n\n\n\n<p>Now we know how to print the <em>ten<\/em> and the <em>Celsius sign<\/em> without spaces.<\/p>\n\n\n\n<p>Unfortunately, by using sep = ''&nbsp; we will also lose the space after the phrase: 'You entered the temperature'. &nbsp;But&nbsp;this is easy to avoid just by typing 'You entered the temperature ' (put&nbsp;a&nbsp;space before you close the quotation).<\/p>\n\n\n<h3 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Degree symbol<\/h3>\n\n\n<p>If you are writing code in a regular Windows notepad, you are probably wondering how to insert the degree symbol:&nbsp;\u00b0<\/p>\n\n\n\n<p>Here is a quick instruction. Call the character table: to do this, press win+R, the Run box will appear, in which type <em>charmap<\/em>. The character table appears.<\/p>\n\n\n\n<p>Choose the symbol you are interested in (e.g. degree sign). Click <em>copy<\/em>. Go to notepad and click <em>paste<\/em>.<\/p>\n\n\n\n<p><\/p>\n\n\n<h2 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Answers to Exercises<\/h2>\n\n<h3 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Celsius to kelvin conversion<\/h3>\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">a=int(input('Enter temperature in Celsius degrees: '))<br>i=0<br>while a&lt;-273:<br>&nbsp;&nbsp;&nbsp; print('Incorrect value')<br>&nbsp;&nbsp;&nbsp; a=int(input('Enter temperature in Celsius degrees: '))<br>&nbsp;&nbsp;&nbsp; i=i+1<br>else:<br>&nbsp;&nbsp;&nbsp; b=a+273<br>&nbsp;&nbsp;&nbsp; print('You have entered temperature ', a, '\u00b0C', sep='')<br>&nbsp;&nbsp;&nbsp; print('In kelvins the temperature is', b)<br>&nbsp;&nbsp;&nbsp; print('Up to now you have entered incorrect temperature', i, 'times.')<br><br><\/p>\n\n<h3 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Do you like&nbsp;candy<\/h3>\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">x=input('Do you like candy? y \/ n&nbsp;&nbsp; ')<br>if&nbsp; x=='y':<br>&nbsp;&nbsp;&nbsp; print('You like candy')<br>else:<br>&nbsp;&nbsp;&nbsp; print('You do not like&nbsp;candy')<br><br><\/p>\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">x=input('Do you like candy? y \/ n&nbsp;&nbsp; ')<br>if&nbsp; x=='y':<br>&nbsp;&nbsp;&nbsp; print('You like candy')<br>print('You do not like&nbsp;candy')<br><br><\/p>\n\n\n<hr class=\"wp-block-separator\">\n\n\n\n<p><a href=\"#_ftnref1\">[1]<\/a> There was only a minor innovation in the third line of code (the sep command; see the Appendix of this article if you want to read a few words of explanation; you will also find a hint on how to insert the degree symbol into your code in the Windows notebook).<\/p>\n\n\n\n<p><a href=\"#_ftnref2\">[2]<\/a> the question arises: why then the Python developers came up with a version of the while loop with an alternate part of the code with else keyword. This version of the code may seem useless. But this is not entirely true. When (in the future) you return to the while loop at a more advanced stage of your learning, you will find that in some specific situations, using else has a different effect than using the same statements in the main&nbsp;code.<\/p>\n\n\n<p class=\"fonts-plugin-block \" style=\"font-weight: normal;color: #E6DBAD\">^<\/p>\n\n<p class=\"fonts-plugin-block \" style=\"font-weight: normal;color: #E6DBAD\">^<\/p>\n\n<p class=\"fonts-plugin-block \" style=\"font-weight: normal;color: #E6DBAD\">^<\/p>\n\n<h1 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Odcinek 5: P\u0119tle w Pythonie<\/h1>\n\n<h3 class=\"fonts-plugin-block \" style=\"font-weight: normal\"><em>Kodujemy w Pythonie<\/em><\/h3>\n\n\n<p>Hello! Jak si\u0119&nbsp;macie.<\/p>\n\n\n\n<p>Dzisiejszy odcinek po\u015bwi\u0119cony jest <strong>p\u0119tlom<\/strong>. Zaczniemy od p\u0119tli while. W programowaniu p\u0119tle s\u0142u\u017c\u0105 do wielokrotnego powtarzania tej samej instrukcji. Nie przesadzimy twierdz\u0105c, \u017ce p\u0119tle to jeden z najwa\u017cniejszych element\u00f3w programowania.<\/p>\n\n\n\n<p>Od czego zaczniemy? Mo\u017ce ma\u0142a rozgrzewka? Napiszmy kr\u00f3tki programik, kt\u00f3ry b\u0119dzie konwertowa\u0142 temperatur\u0119 zapisan\u0105 w stopniach Celsjusza na temperatur\u0119 zapisan\u0105 w Kelvinach. Jak pewnie pami\u0119tasz z lekcji fizyki, skala Kelvina przesuni\u0119ta jest o 273 jednostki w g\u00f3r\u0119 w stosunku do skali Celsjusza. 0\u00b0C to zatem 273 K, 10\u00b0C to 283 K&nbsp;itd.<\/p>\n\n\n\n<p>Oto nasz&nbsp;kod:<\/p>\n\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">a=int(input('Podaj temperatur\u0119 w stopniach Celsjusza: '))<br>b=a+273<br>print('Poda\u0142e\u015b temperatur\u0119 ', a, '\u00b0C', sep='')<br>print('W Kelvinach temperatura ta wynosi:', b)<\/p>\n\n\n<p>Program jest prosty, sk\u0142adnia wszystkich polece\u0144 jest nam znana z poprzednich odcink\u00f3w cyklu<a href=\"#_ftn1\">[1]<\/a>.<\/p>\n\n\n\n<p>Z tych samych lekcji fizyki powiniene\u015b pami\u0119ta\u0107 tak\u017ce, \u017ce temperatura materii nie mo\u017ce by\u0107 ni\u017csza ni\u017c 0 K (zero bezwzgl\u0119dne). Jest to temperatura odpowiadaj\u0105ca \u2011273\u00b0C. Ulepszymy nasz kod poprzez dodanie instrukcji warunkowej, reaguj\u0105cej komunikatem \"Nieprawid\u0142owa warto\u015b\u0107\" na podanie przez u\u017cytkownika temperatury ni\u017cszej ni\u017c \u2011273\u00b0C<\/p>\n\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">a=int(input('Podaj temperatur\u0119 w stopniach Celsjusza: '))<br>if a&lt;-273:<br>&nbsp;&nbsp;&nbsp; print('Nieprawid\u0142owa warto\u015b\u0107')<br>else:<br>&nbsp;&nbsp;&nbsp; b=a+273<br>&nbsp;&nbsp;&nbsp; print('Poda\u0142e\u015b temperatur\u0119 ', a, '\u00b0C', sep='')<br>&nbsp;&nbsp;&nbsp; print('W Kelvinach temperatura ta wynosi:', b)<\/p>\n\n\n<p>Uruchom powy\u017cszy skrypt. Dzia\u0142a bez zarzutu. A jednak\u2026 Nie ca\u0142kiem mo\u017cemy by\u0107 zadowoleni, prawda? Gdy u\u017cytkownik poda nieprawid\u0142ow\u0105 warto\u015b\u0107 temperatury, program skarci go i zako\u0144czy dzia\u0142anie. Czy rzeczywi\u015bcie tak ma dzia\u0142a\u0107 porz\u0105dny program? Jasne, \u017ce nie. Program nie ma prawa si\u0119 wy\u00ad\u0142\u0105cza\u0107 po podaniu przez u\u017cytkownika b\u0142\u0119dnej odpowiedzi, lecz powinien prosi\u0107 go raz za razem o&nbsp;podanie poprawnej odpowiedzi. Do skutku!<\/p>\n\n\n<h2 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Poznajemy p\u0119tle<\/h2>\n\n\n<p>Opisana sytuacja to chleb powszedni programowania. Potrzebujemy, aby program powtarza\u0142 czynno\u015b\u0107 wiele razy. Osi\u0105gniemy to stosuj\u0105c p\u0119tle.<\/p>\n\n\n\n<p>P\u0119tla while (\"r\u00f3b co\u015b dop\u00f3ki\u2026\") jest bardzo podobna w swojej konstrukcji do instrukcji warunkowej if, z t\u0105 r\u00f3\u017cnic\u0105, \u017ce o ile po if Python wykonywa\u0142 zadane polecenia jeden raz, po while wykonywa\u0142 je b\u0119dzie \u2013 jak to si\u0119 m\u00f3wi \u2013 \"w k\u00f3\u0142ko\", a\u017c do momentu, gdy warunek przestanie by\u0107 spe\u0142niony. W&nbsp;naszym przyk\u0142adzie warunkiem jest wpisywanie \"niepoprawnej\" temperatury przez u\u017cytkownika. Je\u015bli u\u017cytkownik uprze si\u0119 i podawa\u0142 b\u0119dzie raz za razem nieprawid\u0142owe temperatury, program uparcie b\u0119dzie go informowa\u0142 \u017ce pope\u0142nia b\u0142\u0105d i od nowa prosi\u0142 o podanie temperatury. Zabawa trwa\u0142a b\u0119dzie do momentu, a\u017c u\u017cytkownik wpisze wreszcie temperatur\u0119 wy\u017csz\u0105 ni\u017c \u2011273\u00b0C.<\/p>\n\n\n\n<p>Napiszmy odpowiedni kod.<\/p>\n\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">a=int(input('Podaj temperatur\u0119 w stopniach Celsjusza: '))<br>while a&lt;-273:<br>&nbsp;&nbsp;&nbsp; print('Nieprawid\u0142owa warto\u015b\u0107')<br>&nbsp;&nbsp;&nbsp; a=int(input('Podaj temperatur\u0119 w stopniach Celsjusza: '))<br>else:<br>&nbsp;&nbsp;&nbsp; b=a+273<br>&nbsp;&nbsp;&nbsp; print('Poda\u0142e\u015b temperatur\u0119 ', a, '\u00b0C', sep='')<br>&nbsp;&nbsp;&nbsp; print('W Kelvinach temperatura ta wynosi:', b)<\/p>\n\n\n<p>Skrypt niewiele si\u0119 r\u00f3\u017cni od tego z instrukcj\u0105 warunkow\u0105 if. Wystarczy\u0142o s\u0142\u00f3wko \"if\" zast\u0105pi\u0107 s\u0142\u00f3w\u00adkiem \"while\" \u2013 rzec by mo\u017cna. No prawie. Opr\u00f3cz tej zmiany musieli\u015bmy \u2013 wewn\u0105trz p\u0119tli while \u2013 powt\u00f3rzy\u0107 pierwsz\u0105 lini\u0119 kodu, t\u0119 z poleceniem input.<\/p>\n\n\n\n<p>Dlaczego? Jest to do\u015b\u0107 oczywiste. Aby Python wielokrotnie powtarza\u0142 wykonanie tej linii&nbsp;kodu.<\/p>\n\n\n\n<p>Polecenia u\u017cyte po s\u0142owie while \u2013 i wci\u0119te o cztery spacje \u2013 stanowi\u0105 tre\u015b\u0107 p\u0119tli (loop body) i ich wykonanie ma charakter powtarzalny.<\/p>\n\n\n<h2 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Konstrukcja p\u0119tli&nbsp;while<\/h2>\n\n\n<p>P\u0119tla while sk\u0142ada si\u0119 z dw\u00f3ch cz\u0119\u015bci: warunku i tre\u015bci p\u0119tli (loop body). Tre\u015b\u0107 p\u0119tli to zestaw (sekwencja) polece\u0144. P\u0119tla wykonuje sekwencj\u0119 polece\u0144 wiele razy, a\u017c podany warunek stanie si\u0119 fa\u0142szywy.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" src=\"http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_00_odc_05-1.jpg\" alt class=\"wp-image-127\" width=\"813\" height=\"162\" srcset=\"http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_00_odc_05-1.jpg 609w, http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_00_odc_05-1-300x60.jpg 300w\" sizes=\"(max-width: 813px) 100vw, 813px\"><\/figure>\n\n\n\n<p>Dodatkowo (jak wida\u0107 na powy\u017cszym schemacie) wyst\u0119puje cz\u0119\u015b\u0107 alternatywna, rozpoczy\u00adnaj\u0105ca si\u0119 od else. &nbsp;Z t\u0105 cz\u0119\u015bci\u0105 alternatywn\u0105 jest \u2013 w przypadku p\u0119tli while \u2013 ma\u0142y k\u0142opot, ale o tym za chwil\u0119.<\/p>\n\n\n\n<p>P\u0119tla while wykonywana jest (potencjalnie) niesko\u0144czon\u0105 ilo\u015b\u0107 razy, tak d\u0142ugo jak Python stwierdza prawdziwo\u015b\u0107 zadanego warunku. Gdy warunek przyjmuje warto\u015b\u0107 Fa\u0142sz, p\u0119tla ko\u0144czy dzia\u0142anie (m\u00f3wimy: nast\u0119puje \"wyj\u015bcie\" z&nbsp;p\u0119tli).<\/p>\n\n\n\n<p>Polecenia wskazane po else wykonywane s\u0105 jednorazowo, w sytuacji wyj\u015bcia z&nbsp;p\u0119tli.<\/p>\n\n\n\n<p>Zmienna, do kt\u00f3rej odwo\u0142uje si\u0119 p\u0119tla while, musi by\u0107 wcze\u015bniej zdefiniowana w programie (przed otwarciem p\u0119tli), aby p\u00f3\u017aniej mog\u0142a by\u0107 ponownie u\u017cyta wewn\u0105trz p\u0119tli. St\u0105d \u2013 w naszym przyk\u0142adzie &nbsp;linia a=int(input('Podaj temperatur\u0119 w stopniach Celsjusza: ')) pojawia si\u0119 dwa razy. Najpierw przed p\u0119tl\u0105, p\u00f3\u017aniej wewn\u0105trz niej. Wr\u00f3cimy jeszcze do&nbsp;tego\u2026<\/p>\n\n\n<h2 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Przyk\u0142ad u\u017cycia p\u0119tli&nbsp;while<\/h2>\n\n\n<p>Zilustrujmy p\u0119tl\u0119 while najprostszym mo\u017cliwym przyk\u0142adem, kr\u00f3tszym i chyba \u0142atwiejszym ni\u017c nasz wcze\u015bniejszy przyk\u0142ad konwertuj\u0105cy stopnie Celsjusza na Kelviny.<\/p>\n\n\n\n<p>Przyk\u0142ad ten drukuje warto\u015b\u0107 zmiennej i kt\u00f3ra ma pocz\u0105tkowo warto\u015b\u0107 zero, a za ka\u017cdym przebiegiem p\u0119tli ulega zwi\u0119kszeniu o 1. P\u0119tla dzia\u0142a tak d\u0142ugo, dop\u00f3ki warto\u015b\u0107 i jest mniejsza od&nbsp;5<\/p>\n\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">i=0<br>while i&lt;5:<br>&nbsp;&nbsp;&nbsp; print('numer:', i)<br>&nbsp;&nbsp;&nbsp; i=i+1<br><br><\/p>\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">Output:<br>numer: 0<br>numer: 1<br>numer: 2<br>numer: 3<br>numer: 4<br><br><\/p>\n\n\n<p>Z przyk\u0142adu tego dobrze wida\u0107, \u017ce p\u0119tla \u2013 w swoim pierwszym obiegu \u2013 odwo\u0142uje si\u0119 do warto\u015bci zmiennej podanej przed p\u0119tl\u0105 (i=0) by nast\u0119pnie si\u0119ga\u0107 po warto\u015bci aktualizowane (za ka\u017cdym obiegiem p\u0119tli) lini\u0105 kodu i=i+1, czyli \u2013 inaczej m\u00f3wi\u0105c \u2013 zwi\u0119kszane za ka\u017cdym obiegiem o&nbsp;1.<\/p>\n\n\n\n<p>Taka jest w\u0142a\u015bnie idea p\u0119tli while: na dzie\u0144 doby sprawd\u017a warto\u015b\u0107 pocz\u0105tkow\u0105, wyst\u0119puj\u0105c\u0105 w kodzie przed p\u0119tl\u0105; potem aktualizuj t\u0119 warto\u015b\u0107 i ponownie sprawdzaj.<\/p>\n\n\n\n<p>P\u0119tla tak d\u0142ugo generuje polecenie print, dop\u00f3ki warto\u015b\u0107 i&lt;5. Dlatego output (rozumiany jako wydruk na ekranie) obejmuje liczby od 0 do 4. Zwr\u00f3\u0107 jednak uwag\u0119, \u017ce ostatni obieg p\u0119tli \u2013 ju\u017c po wygene\u00adrowaniu napisu \"numer: 4\", niejako na \"sam koniec\" podnosi warto\u015b\u0107 zmiennej o kolejn\u0105 \"jedynk\u0119\". Finalnie, zmienna i ma zatem warto\u015b\u0107 5.<\/p>\n\n\n\n<p>Gdyby\u015b zmieni\u0142 kolejno\u015b\u0107 linii w kodzie i zapisa\u0142 skrypt w takiej postaci:<\/p>\n\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">i=0<br>while i&lt;5:<br>&nbsp;&nbsp;&nbsp; i=i+1<br>&nbsp;&nbsp;&nbsp; print('numer:', i)<br>&nbsp;&nbsp;&nbsp;<\/p>\n\n\n<p>twoja p\u0119tla while wygeneruje nast\u0119puj\u0105cy output:<\/p>\n\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">numer: 1<br>numer: 2<br>numer: 3<br>numer: 4<br>numer: 5<\/p>\n\n\n<p>Korzy\u015b\u0107 z tego taka, \u017ce ostatnia drukowana warto\u015b\u0107 zmiennej jest r\u00f3wna aktualnej warto\u015bci wyliczonej przez program. Niekorzy\u015b\u0107 natomiast sprowadza si\u0119 do tego, \u017ce nie spe\u0142niamy warunku: \"drukuj warto\u015bci, dop\u00f3ki s\u0105 mniejsze od&nbsp;5\".<\/p>\n\n\n\n<p>Kt\u00f3ra z wersji programu jest lepsza? Nie ma na to odpowiedzi. Wa\u017cne, aby\u015b pisa\u0142 kod z dok\u0142adn\u0105 \u015bwiadomo\u015bci\u0105 uzyskiwanego rezultatu jego uruchomienia.<\/p>\n\n\n<h2 class=\"fonts-plugin-block \" style=\"font-weight: normal\">A co w sytuacji wyj\u015bcia z&nbsp;p\u0119tli?<\/h2>\n\n\n<p>Jak pami\u0119tamy, gdy dochodzi do wyj\u015bcia z p\u0119tli (warunek przyjmuje warto\u015b\u0107 False), Python wykona blok wskazany przez s\u0142owo else \u2013 i nast\u0119puj\u0105ce po nim polecenia \u2013 zapisane z wci\u0119ciem o cztery spacje.<\/p>\n\n\n\n<p>Rozbudujmy nasz program, aby \u2013 gdy nast\u0119puje wyj\u015bcie z p\u0119tli \u2013 drukowany by\u0142 komunikat \"Good&nbsp;bye!\"<\/p>\n\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">i=0<br>while i &lt; 5:<br>&nbsp;&nbsp;&nbsp; print('number:', i)<br>&nbsp;&nbsp;&nbsp; i=i+1<br>else:<br>&nbsp;&nbsp;&nbsp; print('Good bye!')<br><br>print('A teraz dalszy ci\u0105g programu.')<br><br>Output:<br>number: 0<br>number: 1<br>number: 2<br>number: 3<br>number: 4<br>Good bye!<br>A teraz dalszy ci\u0105g programu.<\/p>\n\n\n<p>Komentarz: program wykonuje p\u0119tl\u0119 pi\u0119ciokrotnie, nast\u0119pnie wykonuje <strong>kod alterantywny<\/strong> (else), wreszcie przechodzi do wykonania polece\u0144 poza p\u0119tl\u0105 \u2013 w kodzie g\u0142\u00f3wnym (w naszym przyk\u0142adzie wygenerowanie napisu \"A teraz dalszy ci\u0105g programu.\").<\/p>\n\n\n<h3 class=\"fonts-plugin-block \" style=\"font-weight: normal\">\u0106wiczenie<\/h3>\n\n\n<p>Rozbuduj skrypt konwertuj\u0105cy temperatur\u0119 ze stopni Celsjusza na Kelviny.<\/p>\n\n\n\n<p>Dodaj kod pozwalaj\u0105cy zliczy\u0107, ile razy u\u017cytkownik poda\u0142 nieprawid\u0142ow\u0105 warto\u015b\u0107 temperatury.<\/p>\n\n\n\n<p>Zapisz polecenie, kt\u00f3re na sam koniec wydrukuje komunikat:<\/p>\n\n\n\n<p>\"Wcze\u015bniej i razy poda\u0142e\u015b nieprawid\u0142ow\u0105 warto\u015b\u0107 temperatury.\"<\/p>\n\n\n\n<p>- gdzie w miejscu literki i pojawia\u0107 si\u0119 b\u0119dzie \u2013 rzecz jasna \u2013 faktyczna liczba nieprawid\u0142owych poda\u0144.<\/p>\n\n\n<h3 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Zagadka<\/h3>\n\n\n<p>Przegl\u0105daj\u0105c (cho\u0107by w internecie) rozmaite przyk\u0142ady zastosowania p\u0119tli while w j\u0119zyku Python, trafi\u0107&nbsp;mo\u017cemy na skrypty bardzo podobne do naszego skryptu drukuj\u0105cego kolejne liczby od 0 do&nbsp;4.<\/p>\n\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">i=0<br>while i &lt; 5:<br>&nbsp;&nbsp;&nbsp; print('numer:', i)<br>&nbsp;&nbsp;&nbsp; i=i+1<br>print('Good bye!')<br>print('A teraz dalszy ci\u0105g programu.')<\/p>\n\n\n<p>Output:<\/p>\n\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">numer: 0<br>numer: 1<br>numer: 2<br>numer: 3<br>numer: 4<br>Good bye!<br>A teraz dalszy ci\u0105g programu.<\/p>\n\n\n<p>Przyk\u0142ad podobny, cho\u0107 nie taki sam jak poprzednio. Kod skryptu r\u00f3\u017cni si\u0119 od poprzedniego, prawda? Brakuje else. Polecenie, kt\u00f3re nast\u0119powa\u0142o po else \u2013 i by\u0142o wci\u0119te o cztery spacje \u2013 teraz umiesz\u00adczone jest w kodzie g\u0142\u00f3wnym. Natomiast output jest identyczny jak poprzednio.<\/p>\n\n\n\n<p>Skoro output jest identyczny z else i bez else, to czy to znaczy, \u017ce \u2013 w przypadku p\u0119tli while \u2013 else jest zb\u0119dne? Tak. Odpowied\u017a jest twierdz\u0105ca. Nie musimy korzysta\u0107 z else, a polecenia, kt\u00f3re chcemy realizowa\u0107 przy wyj\u015bciu z p\u0119tli, mo\u017cemy umieszcza\u0107 po prostu w kodzie g\u0142\u00f3wnym<a href=\"#_ftn2\">[2]<\/a>.<\/p>\n\n\n\n<p>A czy takie samo uproszczenie, to znaczy umieszczenie polece\u0144 alternatywnych bezpo\u015brednio w kodzie g\u0142\u00f3wnym, mo\u017cliwe jest do zastosowania w przypadku instrukcji warunkowej if?<\/p>\n\n\n\n<p>Odpowied\u017a brzmi: zdecydowanie nie.<\/p>\n\n\n\n<p>Ale w\u0142a\u015bciwie dlaczego? Przecie\u017c while i if wydawa\u0142y si\u0119 logicznie tak do siebie podobne\u2026<\/p>\n\n\n\n<p>No w\u0142a\u015bnie. Tylko \"wydawa\u0142y si\u0119\" niestety. Spr\u00f3bujmy rozwik\u0142a\u0107 t\u0119 zagadk\u0119.<\/p>\n\n\n<h2 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Gdzie tkwi r\u00f3\u017cnica<\/h2>\n\n\n<p>Na pocz\u0105tku naszego kursu stwierdzili\u015bmy, \u017ce nauka programowania rozwija zdolno\u015b\u0107 logicznego my\u015blenia. Czas sprawdzi\u0107 to \"w&nbsp;akcji\".<\/p>\n\n\n\n<p>Pokazanie, \u017ce else spe\u0142nia inn\u0105 rol\u0119 w przypadku instrukcji warunkowej if, a inn\u0105 w przypadku p\u0119tli while, to \u015bwietny trening dla szarych kom\u00f3rek.<\/p>\n\n\n\n<p>Zacznijmy od narysowania prostego diagramu. Gdy Python zrealizuje czy to instrukcj\u0119 warunkow\u0105 if, czy p\u0119tl\u0119 while, przechodzi nast\u0119pnie do kolejnych polece\u0144 kodu g\u0142\u00f3wnego.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" src=\"http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_01_odc_05.jpg\" alt class=\"wp-image-129\" width=\"880\" height=\"178\" srcset=\"http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_01_odc_05.jpg 633w, http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_01_odc_05-300x61.jpg 300w\" sizes=\"(max-width: 880px) 100vw, 880px\"><\/figure>\n\n\n\n<p>Wykonanie \u2013 czy to instrukcji warunkowej czy p\u0119tli while \u2013 zaczyna si\u0119 zawsze od sprawdzenia warunku (condition). Python sprawdza, czy przy danej warto\u015bci zmiennej, warunek przyj\u0105\u0142 warto\u015b\u0107 True, czy False. Pami\u0119tamy to, prawda?<\/p>\n\n\n\n<p>Sedno r\u00f3\u017cnicy tkwi w tym, \u017ce w przypadku instrukcji warunkowej, przej\u015bcie do kolejnych polece\u0144 kodu g\u0142\u00f3wnego jest mo\u017cliwe zar\u00f3wno w sytuacji, gdy warunek przyj\u0105\u0142 warto\u015b\u0107 True, jak i&nbsp;False.<\/p>\n\n\n\n<p>Natomiast w przypadku p\u0119tli, przej\u015bcie do kolejnych polece\u0144 kodu g\u0142\u00f3wnego jest mo\u017cliwe tylko gdy warunek przyj\u0105\u0142 warto\u015b\u0107 False. W sytuacji, gdy warunek przyjmuje warto\u015b\u0107 True, Python nie si\u0119ga po dalsze linie kodu. Obraca si\u0119 \"w miejscu\" (w p\u0119tli), to znaczy aktualizuje warto\u015b\u0107 zmiennej i znowu sprawdza prawdziwo\u015b\u0107 warunku, i znowu aktualizuje, i znowu sprawdza, i tak w k\u00f3\u0142ko. Gdyby waru\u00adnek bezustannie wykazywa\u0142 warto\u015b\u0107 True, obracaliby\u015bmy si\u0119 w p\u0119tli w niesko\u0144czono\u015b\u0107.<\/p>\n\n\n\n<p>Skoro \u2013 w przypadku p\u0119tli while \u2013 przej\u015bcie do kolejnych polece\u0144 kodu g\u0142\u00f3wnego jest mo\u017cliwe tylko gdy warunek przyjmie warto\u015b\u0107 False, program <strong>musi<\/strong> wykona\u0107 cze\u015b\u0107 kodu zwi\u0105zan\u0105 z else (gdy\u017c z definicji cz\u0119\u015b\u0107 alternatywna kodu wykonywana jest w\u00f3wczas, gdy warunek przyjmuje warto\u015b\u0107 False).<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" src=\"http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_02_odc_05.jpg\" alt class=\"wp-image-131\" width=\"876\" height=\"402\" srcset=\"http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_02_odc_05.jpg 636w, http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_02_odc_05-300x138.jpg 300w\" sizes=\"(max-width: 876px) 100vw, 876px\"><\/figure>\n\n\n\n<p><strong>W przypadku p\u0119tli while przej\u015bcie przez program do realizacji \"kolejnych linii kodu g\u0142\u00f3wnego\" jest mo\u017cliwe <u>tylko<\/u> w przypadku przyj\u0119cia przez warunek warto\u015bci False.<\/strong><\/p>\n\n\n\n<p>A jaka jest konsekwencja przyj\u0119cia przez warunek warto\u015bci False? W\u00f3wczas wykonywane jest polecenie alternatywne (fragment kodu wyst\u0119puj\u0105cy po s\u0142owie else).<\/p>\n\n\n\n<p>Jaki wniosek z tego p\u0142ynie? W przypadku p\u0119tli while (inaczej ni\u017c w przypadku instrukcji if) pomi\u00adni\u0119cie wykonania polecenia alternatywnego <strong>jest niemo\u017cliwe<\/strong>. Niemo\u017cliwe jest wyj\u015bcie z p\u0119tli przy warto\u015bci warunku True, z pomini\u0119ciem cz\u0119\u015bci else.<\/p>\n\n\n\n<p>W programowaniu zadaniem else jest umo\u017cliwienie&nbsp; \u2013 pod okre\u015blonym warunkiem \u2013 pomini\u0119cia wykonania tej cz\u0119\u015bci kodu, kt\u00f3ra nast\u0119puje po else i jest wci\u0119ta o cztery spacje. Skoro w przypadku p\u0119tli while takie pomini\u0119cie nie jest mo\u017cliwe, else staje si\u0119 zb\u0119dne. Polecenia, kt\u00f3re chcemy wykona\u0107, mog\u0105 by\u0107 zapisane wprost w kodzie g\u0142\u00f3wnym.<\/p>\n\n\n\n<p>Ujmuj\u0105c najkr\u00f3cej: polecenie alternatywne na pewno zostanie wykonane<a href=\"#_ftn3\">[3]<\/a>. A skoro polecenie alter\u00adnatywne na pewno zostanie wykonane, po co pisa\u0107 przed nim \"else\"?<\/p>\n\n\n\n<p>Dlatego powt\u00f3rzmy: u\u017cywanie else w przypadku p\u0119tli while niespecjalnie ma sens. Wi\u0119kszo\u015b\u0107 programist\u00f3w pomija else i zestaw polece\u0144 do wykonania w przypadku wyj\u015bcia z p\u0119tli zapisuje po&nbsp;prostu w kodzie g\u0142\u00f3wnym.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" src=\"http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_03_odc_05.jpg\" alt class=\"wp-image-133\" width=\"778\" height=\"208\" srcset=\"http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_03_odc_05.jpg 629w, http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_03_odc_05-300x80.jpg 300w\" sizes=\"(max-width: 778px) 100vw, 778px\"><\/figure>\n\n\n<h3 class=\"fonts-plugin-block \" style=\"font-weight: normal\">\u0106wiczenie<\/h3>\n\n\n<p>Napisz kr\u00f3tki program, zadaj\u0105cy u\u017cytkownikowi pytanie: 'Czy lubisz cukierki? t \/&nbsp;n&nbsp;'<\/p>\n\n\n\n<p>Zastosuj instrukcj\u0119 warunkow\u0105 if\u2026 else\u2026, kt\u00f3ra zr\u00f3\u017cnicuje odpowied\u017a programu zale\u017cnie od wci\u015bni\u0119cia przez&nbsp;u\u017cytkownika literki t lub&nbsp;n.<\/p>\n\n\n\n<p>Przyk\u0142adowo gdy u\u017cytkownik wci\u015bnie t, program b\u0119dzie drukowa\u0142 komunikat: 'Lubisz cukierki', za\u015b&nbsp;gdy wci\u015bnie n, komunikat: 'Nie lubisz cukierk\u00f3w'.<\/p>\n\n\n\n<p>Uruchom program i wybierz t. Uruchom ponownie i wybierz n. Zaobserwuj efekt.<\/p>\n\n\n\n<p>Nast\u0119pnie dokonaj zmian w skrypcie, usuwaj\u0105c s\u0142\u00f3wko else, za\u015b polecenie alternatywne umie\u015b\u0107 w&nbsp;kodzie g\u0142\u00f3wnym.<\/p>\n\n\n\n<p>Uruchom program i wybierz t. Uruchom ponownie i wybierz n. Zaobserwuj efekt.<\/p>\n\n\n\n<p>Teraz napisz nowy skrypt, kt\u00f3ry pos\u0142ugiwa\u0142 si\u0119 b\u0119dzie p\u0119tl\u0105 &nbsp;while\u2026 else\u2026 , zamiast instrukcj\u0105 warunkow\u0105 if\u2026&nbsp;else\u2026.<\/p>\n\n\n\n<p>Przetestuj dzia\u0142anie. Dokonaj analogicznych zmian jak poprzednio i znowu przetestuj.<\/p>\n\n\n<h2 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Podsumowanie<\/h2>\n\n\n<p>Z dzisiejszego odcinka zapami\u0119taj:<\/p>\n\n\n\n<ul><li>p\u0119tle w Pythonie s\u0142u\u017c\u0105 wielokrotnemu wykonaniu fragmentu kodu<\/li><li>przyk\u0142adem p\u0119tli jest p\u0119tla while, kt\u00f3ra dzia\u0142a tak d\u0142ugo, dop\u00f3ki okre\u015blony warunek jest spe\u0142niony<\/li><li>p\u0119tla while jest podobna do instrukcji warunkowej if z t\u0105 r\u00f3\u017cnic\u0105, \u017ce o ile if sprawdza warunek jeden raz, while sprawdza warunek wielokrotnie: raz za razem a\u017c do momentu, gdy przyjmie on warto\u015b\u0107 False. Z tego powodu p\u0119tla ta \u015bwietnie przyda Ci si\u0119 w sytuacji, gdy chcesz wymusi\u0107 na u\u017cytkowniku podanie racjonalnej odpowiedzi na zadane przez program pytanie.<\/li><li>pomimo podobie\u0144stwa do if, logika dzia\u0142ania while jest odmienna w zakresie kodu alternatywnego nast\u0119puj\u0105cego po s\u0142owie else<\/li><\/ul>\n\n\n<h2 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Dodatek: Ze spacj\u0105 czy&nbsp;bez<\/h2>\n\n\n<p>Polecenie &nbsp;print('Poda\u0142e\u015b temperatur\u0119 ', a, '\u00b0C') \u0142\u0105czy trzy elementy:<\/p>\n\n\n\n<ul><li>\u0142a\u0144cuch znak\u00f3w: 'Poda\u0142e\u015b temperatur\u0119'<\/li><li>zmienn\u0105 a (kt\u00f3ra ma warto\u015b\u0107 liczbow\u0105)<\/li><li>\u0142a\u0144cuch znak\u00f3w: '\u00b0C'<\/li><\/ul>\n\n\n\n<p>Takie elementy \u0142\u0105czymy (jak wida\u0107) przecinkami. \u0141\u0105czenie przy u\u017cyciu znaku '+' by\u0142oby mo\u017cliwe tylko je\u015bli wszystkie trzy elementy by\u0142yby typu 'tekst'. Gdy \u0142\u0105czymy &nbsp;elementy r\u00f3\u017cnego typu (tekst i&nbsp;liczby), skazani jeste\u015bmy na przecinki.<\/p>\n\n\n\n<p>Python \u2013 dokonuj\u0105c wydruku \u2013 domy\u015blnie rozdziela podane elementy znakiem spacji.<\/p>\n\n\n\n<p>Przeprowad\u017a test. Napisz w shellu:<\/p>\n\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">print('Poda\u0142e\u015b temperatur\u0119', 10, '\u00b0C')<\/p>\n\n\n<p>i naci\u015bnij Enter. Powiniene\u015b uzyska\u0107 taki&nbsp;efekt:<\/p>\n\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">Poda\u0142e\u015b temperatur\u0119 10 \u00b0C<\/p>\n\n\n<p>Je\u015bli jeste\u015b perfekcjonist\u0105, uzyskany efekt pewnie Ci\u0119 nie zadowala, poniewa\u017c symbol stopni Celsjusza (\u00b0C) nie powinien by\u0107 oddzielony spacj\u0105 od liczby 10.<\/p>\n\n\n\n<p>Prawid\u0142owo zapisuje si\u0119: 10\u00b0C a nie 10  \u00b0C.<\/p>\n\n\n\n<p>Jak pozby\u0107 si\u0119 niechcianej spacji?<\/p>\n\n\n\n<p>Ca\u0142kiem prosto. Python co prawda domy\u015blnie u\u017cywa spacji jako separatora w poleceniu print, jednak pozwala programi\u015bcie zdefiniowa\u0107 inny separator, je\u015bli programista ma na to ochot\u0119. Dokonuje si\u0119 tego pisz\u0105c sep=   i podaj\u0105c w cudzys\u0142owie wybrany separator, np. my\u015blnik albo kropk\u0119:<\/p>\n\n\n\n<p>sep='-'&nbsp; # taki zapis definiuje my\u015blnik jako separator<\/p>\n\n\n\n<p>Gdy nie \u017cyczysz sobie \u017cadnego separatora, napisz sep=''&nbsp; # czyli u\u017cyj pustego cudzys\u0142owu<\/p>\n\n\n\n<p>Teraz ju\u017c wiemy jak wydrukowa\u0107 dziesi\u0105tk\u0119 i znak stopni Celsjusza bez spacji.<\/p>\n\n\n\n<p>Niestety przy okazji utracimy tak\u017ce spacj\u0119 po frazie: 'Poda\u0142e\u015b temperatur\u0119'.<\/p>\n\n\n\n<p>Aby po s\u0142owach 'Poda\u0142e\u015b temperatur\u0119' mimo wszystko pojawi\u0142a si\u0119 spacja, po prostu wstaw znak spacji &nbsp;zanim zamkniesz cudzys\u0142\u00f3w.<\/p>\n\n\n\n<p>Zamiast:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" src=\"http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_04_odc_05.jpg\" alt class=\"wp-image-139\" width=\"279\" height=\"44\"><\/figure>\n\n\n\n<p>Napisz:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" src=\"http:\/\/juthon.com\/wp-content\/uploads\/2021\/06\/Tab_05_odc_05.jpg\" alt class=\"wp-image-140\" width=\"293\" height=\"43\"><\/figure>\n\n\n<h3 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Symbol stopnia<\/h3>\n\n\n<p>Je\u017celi piszesz kod w zwyk\u0142ym notatniku Windows, pewnie zastanawiasz si\u0119, jak wstawi\u0107 symbol stopnia:&nbsp;\u00b0<\/p>\n\n\n\n<p>Oto kr\u00f3tka instrukcja. Wywo\u0142aj tablic\u0119 znak\u00f3w: w tym celu naci\u015bnij win+R, pojawi si\u0119 pole Uruchamianie, w kt\u00f3rym wpisz charmap. Pojawi si\u0119 tablica znak\u00f3w.<\/p>\n\n\n\n<p>Wybierz symbol, kt\u00f3ry Ci\u0119 interesuje (np. znak stopnia).<\/p>\n\n\n\n<p>Kliknij <em>kopiuj<\/em>.<\/p>\n\n\n\n<p>Przejd\u017a do notatnika i kliknij <em>wklej<\/em>.<\/p>\n\n\n<h2 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Odpowiedzi do \u0107wicze\u0144<\/h2>\n\n<h3 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Konwersja ze stopni celsjusza na kelwiny<\/h3>\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">a=int(input('Enter temperature in Celsius degrees: '))<br>i=0<br>while a&lt;-273:<br>&nbsp;&nbsp;&nbsp; print('Incorrect value')<br>&nbsp;&nbsp;&nbsp; a=int(input('Enter temperature in Celsius degrees: '))<br>&nbsp;&nbsp;&nbsp; i=i+1<br>else:<br>&nbsp;&nbsp;&nbsp; b=a+273<br>&nbsp;&nbsp;&nbsp; print('You have entered temperature ', a, '\u00b0C', sep='')<br>&nbsp;&nbsp;&nbsp; print('In kelvins the temperature is', b)<br>&nbsp;&nbsp;&nbsp; print('Up to now you have entered incorrect temperature', i, 'times.')<br><br><\/p>\n\n<h3 class=\"fonts-plugin-block \" style=\"font-weight: normal\">Czy lubisz cukierki<\/h3>\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">x=input('Do you like candy? y \/ n&nbsp;&nbsp; ')<br>if&nbsp; x=='y':<br>&nbsp;&nbsp;&nbsp; print('You like candy')<br>else:<br>&nbsp;&nbsp;&nbsp; print('You do not like&nbsp;candy')<br><br><\/p>\n\n<p class=\"fonts-plugin-block \" style=\"font-family: consolas;font-weight: normal;font-size: 15px\">x=input('Do you like candy? y \/ n&nbsp;&nbsp; ')<br>if&nbsp; x=='y':<br>&nbsp;&nbsp;&nbsp; print('You like candy')<br>print('You do not like&nbsp;candy')<br><br><\/p>\n\n\n<hr class=\"wp-block-separator\">\n\n\n\n<p><a href=\"#_ftnref1\">[1]<\/a> Pojawi\u0142a si\u0119 jedynie drobna innowacja w trzeciej linii kodu (polecenie sep; zajrzyj do Dodatku do tego artyku\u0142u, je\u015bli chcesz przeczyta\u0107 kilka s\u0142\u00f3w obja\u015bnie\u0144; znajdziesz tam r\u00f3wnie\u017c wskaz\u00f3wk\u0119, jak w notatniku Windows wstawi\u0107 do kodu symbol stopnia).<\/p>\n\n\n\n<p><a href=\"#_ftnref2\">[2]<\/a> pytanie, po co w takim razie tw\u00f3rcy Pythona wymy\u015blili wersj\u0119 p\u0119tli while posiadaj\u0105c\u0105 cz\u0119\u015b\u0107 alternatywn\u0105 w postaci else.<br>Gdy&nbsp;(w przysz\u0142o\u015bci) wr\u00f3cisz do p\u0119tli while w bardziej zaawansowanej fazie twojej nauki, dowiesz si\u0119, \u017ce w pewnych szczeg\u00f3lnych sytuacjach, zastosowanie else daje inny efekt ni\u017c u\u017cycie tych samych polece\u0144 w kodzie g\u0142\u00f3wnym.<\/p>\n\n\n\n<p><a href=\"#_ftnref3\">[3]<\/a> wykluczaj\u0105c rzecz jasna scenariusz kr\u0119cenia si\u0119 w p\u0119tli do ko\u0144ca \u015bwiata<\/p>\n","protected":false},"excerpt":{"rendered":"<p>We code in Python Hello! How are you. Today's passage is devoted to loops. We'll [\u2026]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"wp_typography_post_enhancements_disabled":false},"categories":[1],"tags":[],"_links":{"self":[{"href":"http:\/\/juthon.com\/index.php\/wp-json\/wp\/v2\/posts\/125"}],"collection":[{"href":"http:\/\/juthon.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/juthon.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/juthon.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/juthon.com\/index.php\/wp-json\/wp\/v2\/comments?post=125"}],"version-history":[{"count":10,"href":"http:\/\/juthon.com\/index.php\/wp-json\/wp\/v2\/posts\/125\/revisions"}],"predecessor-version":[{"id":150,"href":"http:\/\/juthon.com\/index.php\/wp-json\/wp\/v2\/posts\/125\/revisions\/150"}],"wp:attachment":[{"href":"http:\/\/juthon.com\/index.php\/wp-json\/wp\/v2\/media?parent=125"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/juthon.com\/index.php\/wp-json\/wp\/v2\/categories?post=125"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/juthon.com\/index.php\/wp-json\/wp\/v2\/tags?post=125"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}