{"id":8119,"date":"2023-10-18T17:33:53","date_gmt":"2023-10-18T12:03:53","guid":{"rendered":"https:\/\/tutorpython.com\/?p=8119"},"modified":"2023-10-19T15:11:02","modified_gmt":"2023-10-19T09:41:02","slug":"python-must-be-real-number-not-str","status":"publish","type":"post","link":"https:\/\/tutorpython.com\/python-must-be-real-number-not-str","title":{"rendered":"Python must be real number not str"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-transparent ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">In This Article<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/tutorpython.com\/python-must-be-real-number-not-str\/#Understanding_TypeError_must_be_real_number_not_str\" >Understanding TypeError: must be real number, not str<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/tutorpython.com\/python-must-be-real-number-not-str\/#User_Input\" >User Input<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/tutorpython.com\/python-must-be-real-number-not-str\/#Data_Processing\" >Data Processing<\/a><\/li><\/ul><\/li><\/ul><\/nav><\/div>\n<p>When doing math-related coding with Python, we might run into the error <code>TypeError: must be real number, not str<\/code>. This error can be puzzling to those new to the language, but in this article, we will demystify the error, diving into why the error might occur, and how to solve it.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Understanding_TypeError_must_be_real_number_not_str\"><\/span>Understanding <code>TypeError: must be real number, not str<\/code><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The error <code>TypeError: must be real number not str<\/code>will occur whenever a <a href=\"https:\/\/tutorpython.com\/tutorial\/types-of-operators-in-python\" target=\"_blank\" rel=\"noopener\">mathematical operation<\/a> is carried out on a <a href=\"https:\/\/tutorpython.com\/tutorial\/strings-in-python\" target=\"_blank\" rel=\"noopener\">string<\/a> (rather than a float or integer). There are several scenarios in which we can encounter the error, and we will examine some of them in the subsections that follow.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"User_Input\"><\/span>User Input<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>On common case that we can encounter the error is when requesting <a href=\"https:\/\/tutorpython.com\/tutorial\/basic-input-output-operations-in-python\" target=\"_blank\" rel=\"noopener\">user input<\/a>. The `input` function returns the user entry as a string, but we make use of the input as it is where a <code>float<\/code> or <code>int<\/code> was expected. For example:<\/p>\n<pre class=\"language-python line-numbers\"><code>import math\r\nresponse = input(\"Enter a number to find logarithm of: \")\r\nresult = math.log10(response)\r\nprint(result)<\/code><\/pre>\n<p>Our code example wants to find the logarithm (base 10) of a number entered by the user. When our code is executed, we get the following;<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-8737\" src=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_userinput_error.png\" alt=\"output TypeError must be real number, not str, during user input\" width=\"1363\" height=\"275\" srcset=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_userinput_error.png 1363w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_userinput_error-300x61.png 300w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_userinput_error-1024x207.png 1024w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_userinput_error-768x155.png 768w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_userinput_error-600x121.png 600w\" sizes=\"(max-width: 1363px) 100vw, 1363px\" \/><\/p>\n<p>The program requests user input, and then prints out an error message <code>TypeError: must be real number, not str<\/code> since we are trying to find the logarithm of a string value.<\/p>\n<p>To remove the error message, we have to parse the user input string into a <code>float<\/code> before making use of it. We can do this using the <code>float()<\/code> function. The next example has the same code but with the corrections effected to remove the error message;<\/p>\n<pre class=\"language-python line-numbers\"><code>import math\r\nresponse = <strong>float<\/strong>(input(\"Enter a number to find logarithm of: \"))\r\nresult = math.log10(response)\r\nprint(result)<\/code><\/pre>\n<p>This version of our code works fine, as we do not have any error message displayed on the output. The output we get this time looks like this;<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-8738\" src=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_userinput_noerror.png\" alt=\"output corrected error TypeError must be real number, not str, during user input\" width=\"1363\" height=\"65\" srcset=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_userinput_noerror.png 1363w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_userinput_noerror-300x14.png 300w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_userinput_noerror-1024x49.png 1024w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_userinput_noerror-768x37.png 768w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_userinput_noerror-600x29.png 600w\" sizes=\"(max-width: 1363px) 100vw, 1363px\" \/><\/p>\n<p>In the code, we passed the return value of the <code>input()<\/code>function as an <a href=\"https:\/\/tutorpython.com\/tutorial\/function-arguments-in-python\" target=\"_blank\" rel=\"noopener\">argument<\/a> of <code>float()<\/code>. The <code>math.log10<\/code>function now has the correct <a href=\"https:\/\/tutorpython.com\/tutorial\/data-types-in-python\" target=\"_blank\" rel=\"noopener\">data type<\/a> to use in its calculations. Alternatively, we could do the following;<\/p>\n<pre class=\"language-python line-numbers\"><code>import math\r\nresponse = input(\"Enter a number to find logarithm of: \")\r\nresult = math.log10(float(response))\r\nprint(result)<\/code><\/pre>\n<p>The above code also works well. The key is to carry out the conversion before the function <code>math.log10<\/code> makes use of the <code>str<\/code> value from the user input.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Data_Processing\"><\/span>Data Processing<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>In the second scenario, we will try to <a href=\"https:\/\/tutorpython.com\/tutorial\/file-input-output-in-python\" target=\"_blank\" rel=\"noopener\">read values from a <code>data.csv<\/code>file<\/a>, find the sum of each row and write the results to a <code>results.csv<\/code>file. The contents of the <code>data.csv<\/code>file is as follows;<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-8742\" src=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/input_file_data_csv.png\" alt=\"input file data.csv containing two columns of float data\" width=\"1364\" height=\"317\" srcset=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/input_file_data_csv.png 1364w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/input_file_data_csv-300x70.png 300w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/input_file_data_csv-1024x238.png 1024w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/input_file_data_csv-768x178.png 768w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/input_file_data_csv-600x139.png 600w\" sizes=\"(max-width: 1364px) 100vw, 1364px\" \/><\/p>\n<p>Our `data.csv` file contains three rows of data; each row has two columns of <code>float<\/code>data (as <code>str<\/code>since everything in the CSV file is a string). The following code tries to read the <code>data.csv<\/code>, sum of each column, then write the results to an output file.<\/p>\n<p>However, our code will not run successfully.<\/p>\n<pre class=\"language-python line-numbers\"><code>import math\r\nimport csv\r\n\r\n# Open the input and output CSV files\r\nwith open('data.csv', 'r') as rcsv, open('result.csv', 'w', newline='') as wcsv:\r\n    reader = csv.reader(rcsv)\r\n    writer = csv.writer(wcsv)\r\n    \r\n    # Read and write the header row to the output file\r\n    header = next(reader)  # Skip and store the header row\r\n    writer.writerow(header + [\"sum\"])  # Include the \"sum\" column in the header\r\n\r\n    for row in reader:\r\n        value1 = row[0]\r\n        value2 = row[1]\r\n        total = math.fsum([value1, value2])\r\n\r\n        # Write the row with sum to the output file\r\n        writer.writerow([value1, value2, total])\r\n\r\nprint(f\"Results successfully written to 'results.csv'.\")<\/code><\/pre>\n<p>Can you find out why our code will display an error message?<\/p>\n<p>It is because while making use of <code>math.fsum<\/code>, we did not convert the values from the row to float. Instead, we passed a <a href=\"https:\/\/tutorpython.com\/tutorial\/list-in-python\" target=\"_blank\" rel=\"noopener\">list<\/a> of <code>str<\/code>objects into <code>math.fsum<\/code>. See the output below for the error message.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-8740\" src=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_csv_error.png\" alt=\"output TypeError must be real number, not str, when reading csv file\" width=\"1368\" height=\"296\" srcset=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_csv_error.png 1368w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_csv_error-300x65.png 300w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_csv_error-1024x222.png 1024w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_csv_error-768x166.png 768w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_csv_error-600x130.png 600w\" sizes=\"(max-width: 1368px) 100vw, 1368px\" \/><\/p>\n<p>What we simply need to do is to convert each of <code>value1<\/code> and <code>value2<\/code>to <code>float<\/code>type before passing them to <code>math.fsum<\/code>. The corrected code below shows (in bold) the corrections made to our previous code;<\/p>\n<pre class=\"language-python line-numbers\"><code>import math\r\nimport csv\r\n\r\n# Open the input and output CSV files\r\nwith open('data.csv', 'r') as rcsv, open('result.csv', 'w', newline='') as wcsv:\r\n    reader = csv.reader(rcsv)\r\n    writer = csv.writer(wcsv)\r\n    \r\n    # Read and write the header row to the output file\r\n    header = next(reader)  # Skip and store the header row\r\n    writer.writerow(header + [\"sum\"])  # Include the \"sum\" column in the header\r\n\r\n    for row in reader:\r\n        value1 = row[0]\r\n        value2 = row[1]\r\n        total = math.fsum([<strong>float<\/strong>(value1), <strong>float<\/strong>(value2)])\r\n\r\n        # Write the row with sum to the output file\r\n        writer.writerow([value1, value2, total])\r\n\r\nprint(f\"Results successfully written to 'results.csv'.\")<\/code><\/pre>\n<p>This time, we do not get an error message because <code>math.fsum<\/code> is getting <code>float<\/code>arguments, rather than <code>str<\/code>. The `print` function is also successfully executed, as shown below.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-8744\" src=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_csv_noerror.png\" alt=\"output corrected error TypeError must be real number, not str, while reading csv file\" width=\"1361\" height=\"54\" srcset=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_csv_noerror.png 1361w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_csv_noerror-300x12.png 300w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_csv_noerror-1024x41.png 1024w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_csv_noerror-768x30.png 768w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_csv_noerror-600x24.png 600w\" sizes=\"(max-width: 1361px) 100vw, 1361px\" \/><\/p>\n<p>If we take a peek into our output <code>.csv<\/code> file (<code>results.csv<\/code>) we see that our code produced the expected output successfully.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-8743\" src=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_file_result_csv.png\" alt=\"output to csv file after summing columns\" width=\"1370\" height=\"365\" srcset=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_file_result_csv.png 1370w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_file_result_csv-300x80.png 300w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_file_result_csv-1024x273.png 1024w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_file_result_csv-768x205.png 768w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_file_result_csv-600x160.png 600w\" sizes=\"(max-width: 1370px) 100vw, 1370px\" \/><\/p>\n<p>The <code>results.csv<\/code> file has three columns now since we added an extra <code>sum<\/code> column to hold the sum of entries in the previous columns.<\/p>\n<p>The error <code>TypeError: must be real number, not str<\/code> is a common pitfall for Python programmers. however, as we have seen in the above code examples, it can be easily resolved by converting the <code>str<\/code>value into an appropriate numeric type. This will allow your code to behave as expected.<\/p>\n<p>If you liked this tutorial, please you are welcome to check out our <a href=\"https:\/\/tutorpython.com\/blog\">Python free tutorial<\/a> that will certainly help you solve common coding problems in Python. Or if you need a dedicated <a href=\"https:\/\/tutorpython.com\/\" target=\"_blank\" rel=\"noopener\">tutor for Python<\/a> then contact us.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>When doing math-related coding with Python, we might run into the error&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[28],"tags":[],"class_list":["post-8119","post","type-post","status-publish","format-standard","hentry","category-tutorial"],"acf":[],"_links":{"self":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts\/8119","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/comments?post=8119"}],"version-history":[{"count":13,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts\/8119\/revisions"}],"predecessor-version":[{"id":8891,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts\/8119\/revisions\/8891"}],"wp:attachment":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/media?parent=8119"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/categories?post=8119"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/tags?post=8119"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}