{"id":420,"date":"2010-09-23T18:12:05","date_gmt":"2010-09-23T18:12:05","guid":{"rendered":"http:\/\/cemclinux1.math.uwaterloo.ca\/~cscircles\/wordpress\/"},"modified":"2010-09-23T18:12:05","modified_gmt":"2010-09-23T18:12:05","slug":"4-types","status":"publish","type":"page","link":"https:\/\/olescs.hkmu.edu.hk\/python\/4-types\/","title":{"rendered":"4: Types"},"content":{"rendered":"<!-- Please retain this notice and add more notes if you create a new version.<br \/>\nOriginal lesson author: David Pritchard, daveagp@gmail.com, http:\/\/cscircles.ca<br \/>\nLicense: http:\/\/creativecommons.org\/licenses\/by-nc-sa\/3.0\/-->\n<p><em>From this lesson onwards, examples and code input boxes have buttons labelled<\/em> <strong>Open in console<\/strong> <em>and<\/em> <strong>Visualize<\/strong>. <em>Use them to help debug and explore the code.<\/em><\/p>\n<p>In the <a href=\"\/\">Hello, World! program<\/a> we saw that Python was able to repeat a sentence back to us. We have also seen several examples of arithmetic with numbers. Numbers and sentences are fundamentally different objects, and it causes a Python error when you try to mix them in the wrong way:<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform0\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox0'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>Trying to compare a string and a number.<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 84px;'><textarea wrap='off' name='usercode0' id='usercode0'  cols=10 rows=3 readonly='readonly'  style = 'height : 84px;'  class='pyboxCode RO'>\nx = \"Hello, World!\"\ny = 35\nz = max(x, y)<\/textarea><\/div>\n<div id='pbhistory0' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit0' value=' '\/><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(0)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(0,'N')\" ><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse0\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"0\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"be6e76a12e6524cb283e5659895e5c2f\"\/>\n<div id='pbresults0' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit0\").value = \"Run program\";document.getElementById(\"inputInUse0\").value = \"N\";<\/script>\n<\/p>\n<p>As you can see, we get an error saying that the two arguments to <code>max<\/code> are of different types. The error is a good introduction to the rest of the lesson:<\/p>\n<ul>\n<li><code>\"Hello, World!\"<\/code> is a <strong>string<\/strong> value, which is shown as <code>str<\/code> in Python. A string is any sequence of numbers, letters, and punctuation; we will learn more about them in lesson 7A.<\/li>\n<li><code>35<\/code> is an <strong>integer<\/strong> value, which is shown as <code>int<\/code> in Python. An integer just means a <em>whole number<\/em>; for example, 42, -12, and 0 are integers.<\/li>\n<\/ul>\n<p>Using an object of a bad type is a very common cause of errors in programs. It is like trying to drink a sandwich: you can't do it because you can only drink things of liquid type, and a sandwich is of solid type.<\/p>\n<p>You can determine the type of an object by calling the <code>type<\/code> function on it.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform1\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox1'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>Some examples of types.<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 84px;'><textarea wrap='off' name='usercode1' id='usercode1'  cols=10 rows=3 readonly='readonly'  style = 'height : 84px;'  class='pyboxCode RO'>\nprint(type(\"Hello, World!\"))\nprint(type(34))\nprint(type(1.234))<\/textarea><\/div>\n<div id='pbhistory1' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit1' value=' '\/><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(1)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(1,'N')\" ><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse1\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"1\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"768daed3b2e69c5cd5bc93ea45e1fc32\"\/>\n<div id='pbresults1' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit1\").value = \"Run program\";document.getElementById(\"inputInUse1\").value = \"N\";<\/script>\n<\/p>\n<p>(The meaning of <code>class<\/code> is similar to <code>type<\/code>.) The above example demonstrates that numbers are further divided into two different types, <code>int<\/code> which we mentioned above, and <code>float<\/code>, which is used for storing decimal numbers. You should think of <code>float<\/code>s as inexact or approximate values (we will explain more in lesson 7B). You can usually mix <code>float<\/code> values with <code>int<\/code> values, and the result will be another <code>float<\/code>.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform2\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox2'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>Mixing an <code>int<\/code> and a <code>float<\/code>.<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 136px;'><textarea wrap='off' name='usercode2' id='usercode2'  cols=10 rows=5 readonly='readonly'  style = 'height : 136px;'  class='pyboxCode RO'>\nx = 1.2\ny = 2\nz = x * y\nprint(x, y, z)\nprint(type(x), type(y), type(z))<\/textarea><\/div>\n<div id='pbhistory2' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit2' value=' '\/><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(2)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(2,'N')\" ><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse2\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"2\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"6f21ee769bd3e22ec989fbb8a69edbf5\"\/>\n<div id='pbresults2' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit2\").value = \"Run program\";document.getElementById(\"inputInUse2\").value = \"N\";<\/script>\n<\/p>\n<p>In fact,\u00a0what Python really does when you mix a\u00a0<code>float<\/code>\u00a0with an\u00a0<code>int<\/code>\u00a0is that it converts the\u00a0<code>int<\/code>\u00a0to a\u00a0<code>float<\/code>, and then works with the two\u00a0<code>float<\/code>s.<\/p>\n<div class='pybox modeNeutral' id='pybox3'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Multiple Choice Exercise: <\/span><span class='title'>Floating<\/span><\/div><div>If we change <code>1.2<\/code> to <code>1.5<\/code> in the above program, what is first line of output?<\/div><label>Your choice: <\/label><select id=\"pyselect3\"><option value=\"d\" selected>Select one<\/option><option value=\"w\">1.5 2.0 3.0<\/option><option value=\"w\">An error occurs<\/option><option value=\"r\">1.5 2 3.0<\/option><option value=\"w\">1.5 2 3<\/option><\/select><div class='pyboxbuttons'><input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" name=\"slug\" value=\"4.mixing\"\/><input type='submit' style='margin:5px;' value='Check answer' onClick='pbMultiCheck(3)'\/><\/div><div class=\"pbresults\" id=\"pyMultiResults3\"><\/div><div class=\"epilogue\">Correct! We have to explain two facts here, to see why <code>z<\/code> was printed as <code>3.0<\/code>.\n\n<ul>\n\t\n<li>Computing <code>x * y<\/code> is mixing an <code>int<\/code> and a <code>float<\/code>, which Python treats as two <code>float<\/code>s, giving back <code>z<\/code> as a <code>float<\/code>.<\/li>\n\n\t\n<li>The mathematical value of <code>z<\/code> is 1.5 times 2, which is 3, but stored in inexact decimal form, of type <code>float<\/code>. When Python prints any <code>float<\/code>, even if its value is a whole number, it is printed ending with <code><code>.0<\/code><\/code> to clarify that it is an inexact value.<\/li>\n\n<\/ul>\n\nAlso, note that the value and type of <code>y<\/code> never changed.\n<\/div><\/div>\n<p>It is often necessary to change data from one type to another type. Just as you can convert a sandwich from solid to liquid form by using a blender, you can change data from one type to another type using a <strong>typecast function<\/strong>. You write the name of the desired new type in the same way as a function call, for example<\/p>\n<pre>x = float(\"3.4\")\nprint(x-1)<\/pre>changes the string <code>\"3.4\"<\/code> to the float <code>3.4<\/code>, and then prints out <code>2.4<\/code>. Without the typecast, the <a href=\"https:\/\/olescs.hkmu.edu.hk\/python\/console\/?consolecode=x%3D%223.4%22%0Aprint%28x-1%29\" target=\"_blank\">program would crash<\/a>, since it cannot subtract a number from a string.<\/p>\n<p><table class='pywarn'><tr><td class='pywarnleft'><img src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/warning.png'\/><\/td><td class='pywarnright'><span> Sometimes, Python <em>does<\/em> let you combine strings and numbers using arithmetic operators. The statement\u00a0<code><code>print(\"hots\" * 2)<\/code>\u00a0<\/code>prints <code>hotshots<\/code>. Python's rule is that multiplying a string <em>s<\/em> by an integer <em>n<\/em> means to put <em>n<\/em> copies of the string one after another. We'll see later that \"addition of two strings\" is also well-defined in Python.  <\/span><\/td><\/table><\/p>\n<p>Various typecasts behave differently:<\/p>\n<ul>\n<li>converting a <code>float<\/code> to an <code>int<\/code> loses the information after the decimal point, e.g. <code>int(1.234)<\/code> gives <code>1<\/code>, and <code>int(-34.7)<\/code> gives <code>-34<\/code>.<\/li>\n<li>converting a <code>str<\/code> to an <code>int<\/code> causes an error if the string is not formatted exactly like an integer, e.g. <a href=\"https:\/\/olescs.hkmu.edu.hk\/python\/console\/?consolecode=x%20%3D%20int%28%221.234%22%29\" target=\"_blank\"><code>int(\"1.234\")<\/code> causes an error<\/a>.<\/li>\n<li>converting a <code>str<\/code> to a <code>float<\/code> causes an error if the string is not a number, e.g. <a href=\"https:\/\/olescs.hkmu.edu.hk\/python\/console\/?consolecode=x%20%3D%20float%28%22sandwich%22%29\" target=\"_blank\"><code>float(\"sandwich\")<\/code> causes an error<\/a>.<\/li>\n<\/ul>\n<p>A common use of typecasting that we will see soon is to convert user input, which is always a string, to numerical form. Here is a quick illustration.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform4\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox4'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>Example of typecasting.<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 136px;'><textarea wrap='off' name='usercode4' id='usercode4'  cols=10 rows=5 readonly='readonly'  style = 'height : 136px;'  class='pyboxCode RO'>\ninputStr = \"12\"                          # a piece of user input\nprint(\"The input type is\", type(inputStr))\nx = int(inputStr)\nprint(x, \"is of type\", type(x), \"and its square is\", x*x)\nprint(inputStr * inputStr)               # this line should cause an error<\/textarea><\/div>\n<div id='pbhistory4' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit4' value=' '\/><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(4)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(4,'N')\" ><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse4\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"4\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"c7f8b39cee9546a0c8c059ff52a0e7cf\"\/>\n<div id='pbresults4' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit4\").value = \"Run program\";document.getElementById(\"inputInUse4\").value = \"N\";<\/script>\n<\/p>\n<p>Here is one more exercise to finish the lesson.<\/p>\n<p><table class='pywarn'><tr><td class='pywarnleft'><img src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/warning.png'\/><\/td><td class='pywarnright'><span> Because there are now lots of editor commands, some have been moved into the menu labelled <strong>More actions...<\/strong> <\/span><\/td><\/table><\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform5\" method=\"POST\">\n<div class='pybox modeNeutral ' id='pybox5'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Coding Exercise: <\/span><span class='title'>Tasty Typecasting<\/span><\/div>Write a program to help you feed your friends at a party by doing some math about <em>square pizzas<\/em>. Assume the grader defines a string <code>inputStr<\/code> for you, which is a decimal string meaning the side length <em>L<\/em> of the pizza in cm. The area of the pizza should be computed using the formula <em>A = L*L<\/em>. Then, assuming that each person needs to eat 100 cm<sup>2<\/sup> of pizza, compute the number of people it can feed, <em>rounded down to the nearest integer.<\/em>\u00a0<a class=\"hintlink\"  id=\"hintlink6\">Hint<\/a> <\/p>\n<div><em>Example<\/em>: if <code>inputStr<\/code> is <code>\"17.5\"<\/code>, the area will be 306.25 cm<sup>2<\/sup>, so <code>3<\/code> is the correct output.<\/div>\n<p> <div class=\"helpOuter\" style=\"display: none;\"><div class=\"helpInner\"><div style=\"text-align: center\">You need to create an account and log in to ask a question.<\/div><\/div><\/div><div class='pyboxTextwrap pyboxCodewrap RW resizy'  style='height: 526px;'><textarea wrap='off' name='usercode5' id='usercode5'  cols=10 rows=20   class='pyboxCode RW'>\n# delete this comment and enter your code here\n<\/textarea><\/div>\n<div id='pbhistory5' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit5' value=' '\/><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(5)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(5,'Y')\" ><\/td>\n<td><input type='button' name='history' value=\"History\" onclick=\"historyClick(5,'4.pizza')\" ><\/td>\n<\/tr><\/table><select id='pbSelect5' class='selectmore'><option name='more'>More actions...<\/option>\n<option name='help' data-pbonclick=\"helpClick(5);\" >Help<\/option>\n<\/select><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse5\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"5\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"a9ffbb579638836c943821144f643da7\"\/>\n<div id='pbresults5' class='pbresults avoidline'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit5\").value = \"Run program\";document.getElementById(\"inputInUse5\").value = \"N\";<\/script>\n<\/p>\n<p>Once you are done, head over to the next lesson.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>From this lesson onwards, examples and code input boxes have buttons labelled Open in console and Visualize. Use them to help debug and explore the code. In the Hello, World! program we saw that Python was able to repeat a &hellip; <a href=\"https:\/\/olescs.hkmu.edu.hk\/python\/4-types\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"open","template":"","meta":{"footnotes":""},"class_list":["post-420","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/pages\/420"}],"collection":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/comments?post=420"}],"version-history":[{"count":0,"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/pages\/420\/revisions"}],"wp:attachment":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/media?parent=420"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}