{"id":161,"date":"2023-12-17T16:59:47","date_gmt":"2023-12-17T22:59:47","guid":{"rendered":"https:\/\/www.baizhao666.com\/?p=161"},"modified":"2024-07-17T18:47:29","modified_gmt":"2024-07-18T00:47:29","slug":"control-structure-and-text-files","status":"publish","type":"post","link":"https:\/\/www.baizhao666.com\/?p=161","title":{"rendered":"Control Structure and Text files"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">Conditionals<\/h3>\n\n\n\n<p>Similar to other programming languages, python also uses &#8220;if&#8221; statements for conditions. But python uses &#8220;elif&#8221; instead of &#8220;else if&#8221; for following conditions. Besides, python neither use parenthesis (&#8220;()&#8221;) to cover the conditions nor use curly brackets (&#8220;{}&#8221;) to cover the blocks. Instead, it&#8217;s necessary to indent our codes to make sure they are covered by either conditions or loops.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>The if\/elif\/else blocks in python:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>if &lt;condition&gt;:\n    &lt;this will execute if the condition is true&gt;\nelif &lt;new condition&gt;:\n    &lt;this will execute if the previous condition is not true but this new condition is true&gt;\nelif &lt;newer condition&gt;:\n    &lt;this will execute if the previous condition is not true but this newer condition is true&gt;\nelse:\n    &lt;this will execute if all previous conditions are false&gt;<\/code><\/pre><\/div>\n\n\n\n<p>Small note: while we have to start with &#8220;if&#8221;, we can have however many &#8220;elif&#8221;s we want (include none), and the &#8220;else&#8221; is optional.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>&gt;&gt;&gt; x = 15\n&gt;&gt;&gt; if x &gt; 20:  # this statement is false\n...     print(&quot;x is greater than 20.&quot;)\n... else:       # this statement is true\n...     print(&quot;x is less than 20.&quot;)\n... \nx is less than 20.\n\n# more complicated if-elif-else block\n&gt;&gt;&gt; A = 17\n&gt;&gt;&gt; B = 23.4\n&gt;&gt;&gt; if A &gt; 10:\n...     print(&quot;apple&quot;)\n... elif B &gt;= A:\n...     print(&quot;orange&quot;)\n... elif A == 17:\n...     print(&quot;banana&quot;)\n... else:\n...     print(&quot;eggplant&quot;)\n... \napple\n# in the previous codes, A = 17 &gt; 10, the first &quot;if&quot; block will be executed\n# the rest of the codes will not be executed, even though some of them are true<\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Loops<\/h3>\n\n\n\n<p>In python, loops are &#8220;for&#8221; loops and &#8220;while&#8221; loops. Loops are used in some repeated procedures. For example, if we want to add all the number between 1 and 100, instead of doing &#8220;1+2+3+4+&#8230;+100&#8221; manually, it&#8217;s better use a loop to add them together. Both &#8220;for&#8221; and &#8220;while&#8221; loop will keep repeated the codes inside the block until the condition is no longer true. The conditions in &#8220;for&#8221; loops are somehow different from those in &#8220;while&#8221; loops. The variable used in &#8220;while&#8221; loop condition has to be predefined, while it&#8217;s not necessarily in &#8220;for&#8221; loop.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code># the &quot;while&quot; loop will be like:\n&lt;dummy var&gt; = &lt;initial value&gt;\nwhile &lt;dummy var&gt; &lt; &lt;some value&gt;:\n    &lt;repeated codes&gt;\n    &lt;increment the dummy var&gt;\n\n# the &quot;for&quot; loop will be like:\nfor &lt;dummy var&gt; in &lt;iterable container&gt;:\n    &lt;repeated codes&gt;\n\n# add all the numbers between 1 and 100:\n# while loop:\n&gt;&gt;&gt; i = 1\n&gt;&gt;&gt; sum = 0\n&gt;&gt;&gt; while i &lt;= 100:\n...     sum += i\n...     i += 1\n... \n&gt;&gt;&gt; print(sum)\n5050\n# for loop:\n&gt;&gt;&gt; sum = 0\n&gt;&gt;&gt; for i in range(1, 101):\n...     sum += i\n... \n&gt;&gt;&gt; print(sum)\n5050\n\n# we can create a infinite loop in while loop using True in condition:\n&gt;&gt;&gt; i = 1\n&gt;&gt;&gt; while True:\n...    print(i)\n...    i += 1\n\n# Python has a special command called &quot;break&quot; to end a while loop prematurely\n&gt;&gt;&gt; i = 1\n&gt;&gt;&gt; while True:\n...     print(i)\n...     i += 1\n...     if i &gt; 20:\n...             break\n... \n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n\n# we can also use nested &quot;for&quot; loops or &quot;while&quot; loops\n&gt;&gt;&gt; for i in range(1, 10):\n...     print(&quot;i = &quot;, i)\n...     for j in range(1, 10):\n...             print(i * j)\n# note: the dummy vars in nested loop need to be different\n\n# SPECIAL NOTE:\n# we can even add a &quot;else&quot; statement after the loops\n&gt;&gt;&gt; for i in range(10):\n...     print(i)\n... else:\n...     print(&quot;end!&quot;)\n... \n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\nend!\n# the &quot;else&quot; block will be executed right after the loop ends\n# if there is a &quot;break&quot; command that forces the loop end early, the &quot;else&quot; block won&#39;t be executed <\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Functions:<\/h3>\n\n\n\n<p>In python, there are built-in functions like &#8220;print&#8221;, &#8220;type&#8221;, &#8220;range&#8221;, and etc. We can also define our own function for our convenience. It&#8217;s easier to define our own functions in python than other languages, like C, or Java. In C, C++, or Java, a function or method needs to have a return type even though it doesn&#8217;t return anything. But in Python, it&#8217;s not necessary to include the return type. And the types of input arguments are not needed.<\/p>\n\n\n\n<p>The functions are defined as below:<br>def &lt;fun_name&gt;(var_1, var_2):<br>    &lt;this codes will be executed when this function is called&gt;<br>Small notes: the &#8220;def&#8221; keyword is a must, but var_1, var_2, and return statement are not, depending on the need.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-plain\"><code># define a function that multiples two number\n&gt;&gt;&gt; def mul(a, b):\n...     return a * b\n... \n# call the function\n&gt;&gt;&gt; print(mul(10, 20))\n200<\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Text file<\/h3>\n\n\n\n<p>Reading and writing files in other languages might be complicated. We need to interact with file streams, and close the file stream to avoid memory leak. But here in Python, a simple &#8220;with open&#8221; statement can easily open the file and close the file stream automatically.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code># define text file in a function\ndef read_txt():\n    with open(&quot;my_text.txt&quot;, &quot;r&quot;) as f:\n        my_str = f.read()\n    print(my_str)\n    \ndef write_txt(new_str):\n    with open(&quot;my_text.txt&quot;, &quot;w&quot;) as f:\n        f.write(new_str)\n\n# small note:\n# inside open(), we need to declare the &quot;mode&quot; that we intend to use:\n# common mode: &quot;r&quot;-read, &quot;w&quot;-write, &quot;a&quot;-append, &quot;b&quot;-binary file\n# common functions for &quot;f&quot;:\n# read():read the whole file and store every line in to a string\n# readlines(): read the whole file and store every line in to a list\n# readline(): read only one line\n# write(): write a string to the file\n# writelines(iterable container): write the strings in the containers to file<\/code><\/pre><\/div>\n\n\n\n<p>More on files input\/output: if we open a file in &#8220;r&#8221; mode but the file does not exist, python will raise a &#8220;FileNotFoundError&#8221;. But if we open a file in &#8220;w&#8221; mode but the file does not exist, a new file will be created. If the file exists, the content of the file will be override in &#8220;w&#8221; mode. To append the content, we need to use &#8220;a&#8221; for appending.For the files that aren&#8217;t in the same folder of the .py file, use the absolute path for the file name.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Conditionals Similar to other programming languages, python also uses &#8220;if&#8221; statements for conditions. But python uses &#8220;elif&#8221; instead of &#8220;else if&#8221; for following conditions. Besides, python neither use parenthesis (&#8220;()&#8221;) to cover the conditions nor use curly brackets (&#8220;{}&#8221;) to cover the blocks. Instead, it&#8217;s necessary to indent our codes to make sure they are &hellip; <\/p>\n<p class=\"link-more\"><a href=\"https:\/\/www.baizhao666.com\/?p=161\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Control Structure and Text files&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4],"tags":[],"class_list":["post-161","post","type-post","status-publish","format-standard","hentry","category-python"],"_links":{"self":[{"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/posts\/161","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=161"}],"version-history":[{"count":4,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/posts\/161\/revisions"}],"predecessor-version":[{"id":282,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/posts\/161\/revisions\/282"}],"wp:attachment":[{"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=161"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=161"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=161"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}