<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: AnkurRanpariya2005</title>
    <description>The latest articles on Forem by AnkurRanpariya2005 (@ankurranpariya2005).</description>
    <link>https://forem.com/ankurranpariya2005</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F642684%2Fefbe6c6d-3ed4-4b10-b6d8-9f47f80d0bdd.png</url>
      <title>Forem: AnkurRanpariya2005</title>
      <link>https://forem.com/ankurranpariya2005</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/ankurranpariya2005"/>
    <language>en</language>
    <item>
      <title>Read file into character array in C</title>
      <dc:creator>AnkurRanpariya2005</dc:creator>
      <pubDate>Wed, 31 May 2023 06:33:28 +0000</pubDate>
      <link>https://forem.com/ankurranpariya2005/read-file-into-character-array-in-c-5141</link>
      <guid>https://forem.com/ankurranpariya2005/read-file-into-character-array-in-c-5141</guid>
      <description>&lt;p&gt;When you are working in C programming language, you might encounter some problems which require reading a file into character array, like analyzing the frequency of each character, or converting every starting word of all sentences from lower case to upper case, or vice versa. The solution is really easy but probably isn't that simple for people who do not know much about file reading or writing. So in that article, you can learn step-by-step how to read files into character array in C&lt;/p&gt;

&lt;h2&gt;&lt;span&gt;&lt;strong&gt;Open a file in C&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;

&lt;p&gt;The easiest and most popular way to open a file in C is using the 'fopen' function in the format below:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;file = fopen(file_name, "open_mode"); //open the "file-name" file and store the file pointer in the variable 'file'&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The mode parameter of the 'fopen' function specifies the mode in which the file is to be opened. The mode can be one of the following:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;"&lt;strong&gt;r&lt;/strong&gt;": Open file for reading.&lt;/li&gt;
&lt;li&gt;"&lt;strong&gt;w&lt;/strong&gt;": Truncate file to zero length or create a file for writing.&lt;/li&gt;
&lt;li&gt;"&lt;strong&gt;a&lt;/strong&gt;": Append to file or create a file for writing if it does not exist.&lt;/li&gt;
&lt;li&gt;"&lt;strong&gt;r+&lt;/strong&gt;": Open file for reading and writing.&lt;/li&gt;
&lt;li&gt;"&lt;strong&gt;w+&lt;/strong&gt;": Truncate file to zero length or create a file for reading and writing.&lt;/li&gt;
&lt;li&gt;"&lt;strong&gt;a+&lt;/strong&gt;": Append to file or create a file for reading and writing.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;But for some reason, the file may not open properly. To prepare when such a situation like that happens, you should always check the return value of the 'fopen' function to ensure that the file was opened successfully before attempting to read or write to it. Like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// If 'fopen' returns NULL,  print an error message and exit the program 
if (file == NULL) {
      printf("Error: Failed to open file '%s'.\n", file_name);
      return 1;
}&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;&lt;span&gt;&lt;strong&gt;Read file contents character by character&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;

&lt;p&gt;Before reading the file, you must have a character array to store file contents in there. Let's do that
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;char buffer[1000]; //Initialize a char array named 'buffer' with size of 1000&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, it's time to read the file by using 'fgetc'. This function will read one character in the file every time called, and if called repeatedly it will read each subsequent character until the end. Thus, we can use a while loop to make the process become easier.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;int i = 0, c; //c is the intermediate variable, i is the increment variable
while ((c = fgetc(file)) != EOF) {//Read contents until it reach the end of the file
      buffer[i] = c;
      i++;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The example above assumes that the file contains only ASCII characters and that the file size is less than 1000 characters.&lt;/p&gt;

&lt;h3&gt;&lt;span&gt;&lt;strong&gt;Resizable buffer&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;

&lt;p&gt;The buffer array that we previously defined is containing a maximum of 1000 characters. But for many situations, the file size is much larger than that. We can solve this problem by turning our buffer into a resizable one. You can use dynamic memory allocation with the 'malloc', 'realloc' and 'realloc' functions provided by the C standard library.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;char *buffer = NULL; // initialize buffer to NULL
int buffer_size = 0;
/*Open the file here*/
// Read file character by character
int c, i = 0;
while ((c = fgetc(file)) != EOF) {
    // If buffer is full, resize it
    if (i &amp;gt;= buffer_size) {
       buffer_size += 1000; // increase buffer size by 1000 bytes
       buffer = realloc(buffer, buffer_size); // resize buffer
       if (buffer == NULL) {
          printf("Error: Memory allocation failed.\n");
          return 1;
       }
    }
    buffer[i] = c;
    i++;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We use 'realloc' functions in the above code snippet, which proves to be useful because the file size is usually not known in advance. For 'malloc' and 'calloc' functions, they can be used to allocate a block of memory of the specified size to a variable. In this example, you can use like the below:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;buffer = (char*)malloc(1000); //is the same as define char buffer[1000]&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt; You probably won't need to use 'malloc' and 'calloc' in this example. We will meet them again later.

&lt;br&gt;
&lt;/p&gt;
&lt;h3&gt;&lt;span&gt;&lt;strong&gt;File contains non-ASCII characters&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;In C, a string is represented as a sequence of bytes, and the interpretation of those bytes depends on the character encoding. If the file contains non-ASCII characters, you need to use a character encoding that supports those characters, such as UTF-8 or UTF-16.&lt;/p&gt;

&lt;p&gt;For this problem, you should use functions that can handle multibyte characters, such as 'fgetwc' and 'fgetws'. These functions read one wide character (wchar_t) or one wide character string (wchar_t*) at a time, respectively.&lt;/p&gt;

&lt;p&gt;Here are some modifications to the code to make it work when the file contains non-ASCII characters:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;wchar_t buffer[100];
// Open file for reading
file = fopen(filename, "r,ccs=UTF-8");
// Read file contents
wchar_t c;
int i = 0;
while ((c = fgetwc(file)) != WEOF) {
   buffer[i] = c;
   i++;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Also, make sure that the input and output streams are set to the correct encoding to properly display or manipulate the characters. On Unix operating systems like MacOS and Linux, to ensure the output encoding is in UTF-8, you can use the 'setlocale' function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include 
int main()
{
    setlocale(LC_ALL, "en_US.utf8");

    // your code here

    return 0;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;On Windows, you can use the '_setmode' and '_O_U8TEXT' functions to set the output encoding to UTF-8:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include  //_O_U8TEXT
#include  //_setmode()
int main()
{
    _setmode(_fileno(stdout), _O_U8TEXT);

    // your code here

    return 0;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here's an example of a file containing the Vietnamese word "Xin chào!" (Hello) with accent (which are non-ASCII characters), save in UTF-8 encoding:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Xin chào!&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And here is the output of our program after I run it on an online C compiler:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Xin chào!

...Program finished with exit code 0
Press ENTER to exit console.&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;&lt;span&gt;&lt;strong&gt;Read file contents as a whole&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;

&lt;p&gt;If you are not familiar with C then you can skip this step, but I still recommend reading it as an advanced exercise. I want to introduce another way to tackle the "&lt;strong&gt;How to read file into char array in C&lt;/strong&gt;" problem. The new thinking is to not read the file character by character but as a whole, by determining the file size before reading. This is a more complicated solution, but also more effective. &lt;/p&gt;

&lt;p&gt;First, you should define the usual variables: file pointer to open file and buffer to contain character array. Remember you also need the file size as well:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;FILE *fp;
long file_size;
char *buffer;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then you can open the file to read:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fp = fopen("example.txt", "r");
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To know the size of the file, you can use the 'ftell' function. It will tell the byte location of the current position in the file pointer:&lt;br&gt;&lt;code&gt;current_byte = ftell(fp);&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;But wait, the file reading is always start at the beginning of the file. No problem, the 'fseek' function will move the reading control to different positions in the file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fseek(fp, 0, SEEK_END);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can get the file size properly now. After that, let's set the reading control to the beginning again to start reading file contents:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;file_size = ftell(fp);
rewind(fp); move the control to the file's beginning
 
// Allocate memory for the char array
buffer = (char*) malloc(file_size + 1);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The use of the 'malloc' function here is pretty straightforward: allocating memories to create an uninitialized char array with the size of (file_size+1) times 1 byte (size of type char). &lt;/p&gt;

&lt;p&gt;If you want to use the 'calloc' function, here is how:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;buffer = (char*) calloc(file_size + 1, sizeof(char));&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The main difference between 'malloc' and 'calloc' is that 'malloc' only allocates memory without initializing its contents, while 'calloc' both allocates and initializes memory to zero. The main advantage of using 'calloc' is that the allocated memory will already be zeroed out, which can be helpful if you plan to use the char array as a string later.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// Read the file into the char array
fread(buffer, file_size, 1, fp);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;After creating a buffer, you can read the entire file using the 'fread' function, which takes the file pointer, the size of each element to read, the number of elements to read, and the destination array.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// Add a null terminator at the end of the char array
buffer[file_size] = '\0';&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt; You might be wondering before why there is a need to allocate an extra byte to the "&lt;strong&gt;buffer&lt;/strong&gt;". Why not just (file_size) but (file_size + 1)? Here it is, the null terminator will be added at the end of the char array to indicate the end of the string. Actually, if your only mission is to read a file into an array, then this step is unnecessary. But later if you want to print this array as a string, then this is a requirement. String in C is defined to have the last character as a null terminator '\0'.&lt;/p&gt;

&lt;h2&gt;&lt;span&gt;&lt;strong&gt;Cleanup your code&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;

&lt;p&gt;You have opened and used the file, so remember to close it afterward. Simply use the 'fclose' function to free the "file" pointer variable that you had assigned.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fclose(file);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Talking about freeing pointers, remember the "buffer" array that you used to store characters? If you defined it as an allocated memory (pointer), then it's best to free it now to avoid memory leaks.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;free(buffer);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here is an overview of what your solution should look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include 
#include 

int main() {
   FILE *file;
   char filename[] = "example.txt";
   char *buffer = NULL; // initialize buffer to NULL
   int buffer_size = 0;
   int i = 0;

   //Open file for reading
   file = fopen(filename, "r");

   //Check if file opened successfully
   if (file  == NULL) {
      printf("Error: Failed to open file '%s'.\n", filename);
      return 1;
   }

   // Read file character by character
   int c;
   while ((c = fgetc(file)) != EOF) {
      // If buffer is full, resize it
      if (i &amp;gt;= buffer_size) {
         buffer_size += 1000; // increase buffer size by 1000 bytes
         buffer = realloc(buffer, buffer_size); // resize buffer
         if (buffer == NULL) {
            printf("Error: Memory allocation failed.\n");
            return 1;
         }
      }
      buffer[i] = c;
      i++;
   }

   // Close file
   fclose(file);

   // Print the character array
   printf("%s", buffer);

   // Free the dynamically allocated buffer
   free(buffer);

   return 0;
}&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;&lt;span&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;

&lt;p&gt;In this guide, we covered step-by-step solutions to read a file into a character array in C: opening the file, creating a buffer variable, storing the entire contents from the file to the buffer, and finally closing the file and freeing all memory.&lt;/p&gt;

&lt;p&gt;We also discussed how to solve problems when the file size is too large for our initial buffer to handle, or when the file character encoding is non-standard. We have introduced new concepts and some best examples to use them. This will help you familiarize yourself with these situations, giving you access to a wider range of future-use resources. &lt;/p&gt;

</description>
      <category>c</category>
    </item>
    <item>
      <title>Python Float Numeric Data Type</title>
      <dc:creator>AnkurRanpariya2005</dc:creator>
      <pubDate>Tue, 30 May 2023 10:11:12 +0000</pubDate>
      <link>https://forem.com/ankurranpariya2005/python-float-numeric-data-type-kbi</link>
      <guid>https://forem.com/ankurranpariya2005/python-float-numeric-data-type-kbi</guid>
      <description>&lt;p&gt;&lt;a id="introduction"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;A. Introduction&lt;/h2&gt;

&lt;p&gt;Float is one of the data types under the numeric category. See the &lt;a href="https://logiclair.org/1533/python-integer-numeric-data-type"&gt;Integer type&lt;/a&gt; in this tutorial. Python has integer, float, complex, bool, list, tuple, set, range, dictionary, string, and bytes data types. In this tutorial I will only cover the Float type.&lt;/p&gt;

&lt;p&gt;&lt;a id="numeric"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;B. Numeric data type&lt;/h2&gt;

&lt;p&gt;There are three built-in numeric data types in Python.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Integer
Float
Complex
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;There are also two non-built-in numeric data types.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Fraction
Decimal
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Built-in means you don't need to import such data or functionality.&lt;/p&gt;

&lt;p&gt;&lt;a id="float-1"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;C. Float&lt;/h2&gt;

&lt;p&gt;Float or floating-point number may represent a number that is equal to one or more, or a number that is less than one with decimal point. It can be a positive number such as 1.25 or 0.75. It can also be a negative number such as -100.5 or -0.0015. It can also be just 0.0. It can also be a whole number with decimal point such as 40.0.&lt;/p&gt;

&lt;p&gt;Python's float has a maximum value of 1.7976931348623157e+308. Its minimum positive value is 2.2250738585072014e-308.&lt;/p&gt;

&lt;p&gt;You can get these values by running the Python interpreter from your console or command line. Assuming that you already installed Python.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;C:\&amp;gt;python
Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug  1 2022, 21:53:49) [MSC v.1932 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
&amp;gt;&amp;gt;&amp;gt; import sys
&amp;gt;&amp;gt;&amp;gt; max_value = sys.float_info.max
&amp;gt;&amp;gt;&amp;gt; max_value
1.7976931348623157e+308
&amp;gt;&amp;gt;&amp;gt; min_value = sys.float_info.min
&amp;gt;&amp;gt;&amp;gt; min_value
2.2250738585072014e-308
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Output the full digits for maximum value.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; int(max_value)
179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a id="operators"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;D. Operators&lt;/h2&gt;

&lt;p&gt;We usually use operators to manipulate data. I will only cover some common operators that are usually applied for float. The full operator tutorial will cover this.&lt;/p&gt;

&lt;p&gt;Arithmetic operators.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
  &lt;tr&gt;
    &lt;th&gt;Operator&lt;/th&gt;
&lt;th&gt;Name&lt;/th&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;+&lt;/td&gt;
&lt;td&gt;addition&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;-&lt;/td&gt;
&lt;td&gt;subtraction&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;/&lt;/td&gt;
&lt;td&gt;float division&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;%&lt;/td&gt;
&lt;td&gt;remainder, a % b&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;**&lt;/td&gt;
&lt;td&gt;power, a ** b or a ^ b&lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Comparison operators.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
  &lt;tr&gt;
    &lt;th&gt;Operator&lt;/th&gt;
&lt;th&gt;Name&lt;/th&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt; &amp;gt; &lt;/td&gt;
&lt;td&gt;greater than&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt; &amp;gt;= &lt;/td&gt;
&lt;td&gt;greater than or equal&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt; &amp;lt; &lt;/td&gt;
&lt;td&gt;less than&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt; &amp;lt;= &lt;/td&gt;
&lt;td&gt;less than or equal&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt; == &lt;/td&gt;
&lt;td&gt;equal, a == b&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt; != &lt;/td&gt;
&lt;td&gt;not equal, a != b&lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;&lt;a id="arithmetic"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;1. Arithmetic Operators&lt;/h3&gt;

&lt;p&gt;Addition and subtraction&lt;/p&gt;

&lt;p&gt;Open your python interpreter from the terminal by typing python.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;c:\&amp;gt;python
Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug  1 2022, 21:53:49) [MSC v.1932 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
&amp;gt;&amp;gt;&amp;gt; 10.5 + 1.5
12.0
&amp;gt;&amp;gt;&amp;gt; 20.0 - 5.5
14.5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Multiplication&lt;/p&gt;

&lt;p&gt;Use an asterisk symbol for multiplication. The "type()" method gets the type or class of a variable or object.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = 100.5
&amp;gt;&amp;gt;&amp;gt; b = 2.5
&amp;gt;&amp;gt;&amp;gt; c = a * b
&amp;gt;&amp;gt;&amp;gt; c
251.25
&amp;gt;&amp;gt;&amp;gt; type(c)
&amp;lt;class 'float'&amp;gt;
&amp;gt;&amp;gt;&amp;gt; type(a)
&amp;lt;class 'float'&amp;gt;
&amp;gt;&amp;gt;&amp;gt; type(b)
&amp;lt;class 'float'&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Division&lt;/p&gt;

&lt;p&gt;Use the "/" symbol to get the quotient.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = 300.9
&amp;gt;&amp;gt;&amp;gt; b = 200.5
&amp;gt;&amp;gt;&amp;gt; c = a / b
&amp;gt;&amp;gt;&amp;gt; c
1.5007481296758103
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Remainder&lt;/p&gt;

&lt;p&gt;Python has an operator that can calculate the remainder. It is called the modulo operator with symbol &lt;code&gt;%&lt;/code&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = 2.5
&amp;gt;&amp;gt;&amp;gt; b = 6.2
&amp;gt;&amp;gt;&amp;gt; a % b
2.5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Power&lt;/p&gt;

&lt;p&gt;The built-in function pow() will return a number given base and exponent. It can also be expressed using double asterisk.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = 6.4
&amp;gt;&amp;gt;&amp;gt; b = 1.25
&amp;gt;&amp;gt;&amp;gt; pow(a, b)
10.17946532821825
&amp;gt;&amp;gt;&amp;gt; a ** b
10.17946532821825
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a id="comparison"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;2. Comparison operators&lt;/h3&gt;

&lt;p&gt;Greater than operator "&amp;gt;".&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = 1.9
&amp;gt;&amp;gt;&amp;gt; b = 2.1
&amp;gt;&amp;gt;&amp;gt; a &amp;gt; b
False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Greater than or equal to with symbol "&amp;gt;=".&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = 150.0
&amp;gt;&amp;gt;&amp;gt; b = 120.8
&amp;gt;&amp;gt;&amp;gt; a &amp;gt;= b
True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Less than with symbol "&amp;lt;".&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = 10.8
&amp;gt;&amp;gt;&amp;gt; b = 20.0
&amp;gt;&amp;gt;&amp;gt; a &amp;lt; b
True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Less than or equal to with symbol "&amp;lt;=".&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = 250.5
&amp;gt;&amp;gt;&amp;gt; b = 250.5
&amp;gt;&amp;gt;&amp;gt; if a &amp;lt;= b:
...     print("a is less than or equal to b")
... else:
...     print("a is not less than or equal to b")
...
a is less than or equal to b
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Equal with symbol "==".&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = 0.36
&amp;gt;&amp;gt;&amp;gt; b = 0.36
&amp;gt;&amp;gt;&amp;gt; a == b
True
&amp;gt;&amp;gt;&amp;gt;
&amp;gt;&amp;gt;&amp;gt; # another example
&amp;gt;&amp;gt;&amp;gt; a = 50.45
&amp;gt;&amp;gt;&amp;gt; b = 50.40
&amp;gt;&amp;gt;&amp;gt; a == b
False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Not equal with symbol "!=".&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = 1000.36
&amp;gt;&amp;gt;&amp;gt; b = 1000.361
&amp;gt;&amp;gt;&amp;gt; a != b
True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a id="class"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;E. Class float() Constructor&lt;/h2&gt;

&lt;p&gt;Python has a built-in function called "float()" or a class constructor that can set another type into a float type.&lt;/p&gt;

&lt;p&gt;Convert an integer to a float.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = 100
&amp;gt;&amp;gt;&amp;gt; a
100
&amp;gt;&amp;gt;&amp;gt; type(a)
&amp;lt;class 'int'&amp;gt;
&amp;gt;&amp;gt;&amp;gt; b = float(a)
&amp;gt;&amp;gt;&amp;gt; b
100.0
&amp;gt;&amp;gt;&amp;gt; type(b)
&amp;lt;class 'float'&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Convert a numeric string to a float.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = "75.5"
&amp;gt;&amp;gt;&amp;gt; a
'75.5'
&amp;gt;&amp;gt;&amp;gt; type(a)
&amp;lt;class 'str'&amp;gt;
&amp;gt;&amp;gt;&amp;gt; b = float(a)
&amp;gt;&amp;gt;&amp;gt; b
75.5
&amp;gt;&amp;gt;&amp;gt; type(b)
&amp;lt;class 'float'&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a id="float-2"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;F. Float Example&lt;/h2&gt;

&lt;p&gt;Write a python script called "fruit.py" that takes the price of apple per kilogram, the number kilograms to buy and output the total cost.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;fruit.py&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Ask the cost per kilograms.
cost_per_kg = input("How much is the cost of apple per kilogram? ")
cost_per_kg = float(cost_per_kg)  # convert string to float

# Ask how many kilograms to buy.
num_kg = input("How many kilograms to buy? ")
num_kg = float(num_kg)

# Calculate the total cost.
total_cost = cost_per_kg * num_kg
print("total cost: " + str(total_cost))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;execute the script&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;c:\&amp;gt;python fruit.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Put your fruit.py in C drive.&lt;/p&gt;

&lt;p&gt;If the file is in C drive under python_tutorial folder for example, "cd" or change directory to that folder. The command will look like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;c:\python_tutorial&amp;gt;python fruit.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;output&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;How much is the cost of apple per kilogram? 1.44
How many kilograms to buy? 1.5
total cost: 2.16
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a id="float-3"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;G. Float method as_integer_ratio&lt;/h2&gt;

&lt;p&gt;The class float has a method that returns an integer numerator and denominator. It is defined as "float.as_interger_ratio()".&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = 0.25
&amp;gt;&amp;gt;&amp;gt; b = a.as_integer_ratio()
&amp;gt;&amp;gt;&amp;gt; b
(1, 4)
&amp;gt;&amp;gt;&amp;gt; numerator = b[0]
&amp;gt;&amp;gt;&amp;gt; denominator = b[1]
&amp;gt;&amp;gt;&amp;gt; numerator
1
&amp;gt;&amp;gt;&amp;gt; denominator
4
&amp;gt;&amp;gt;&amp;gt; type(numerator)
&amp;lt;class 'int'&amp;gt;
&amp;gt;&amp;gt;&amp;gt; type(denominator)
&amp;lt;class 'int'&amp;gt;
&amp;gt;&amp;gt;&amp;gt; q = numerator / denominator
&amp;gt;&amp;gt;&amp;gt; q
0.25
&amp;gt;&amp;gt;&amp;gt; type(q)
&amp;lt;class 'float'&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a id="rounding"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;H. Rounding a float&lt;/h2&gt;

&lt;p&gt;Python provides a built-in function "round()" to round a float up to a given decimal places. This is useful if you don't need a very accurate number for simplification.&lt;/p&gt;

&lt;p&gt;Round off a number up to two decimal places.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = 7.35514552
&amp;gt;&amp;gt;&amp;gt; type(a)
&amp;lt;class 'float'&amp;gt;
&amp;gt;&amp;gt;&amp;gt; b = round(a, 2)
&amp;gt;&amp;gt;&amp;gt; b
7.36
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
    </item>
    <item>
      <title>Python Integer Numeric Data Type</title>
      <dc:creator>AnkurRanpariya2005</dc:creator>
      <pubDate>Mon, 29 May 2023 11:46:50 +0000</pubDate>
      <link>https://forem.com/ankurranpariya2005/python-integer-numeric-data-type-1p6f</link>
      <guid>https://forem.com/ankurranpariya2005/python-integer-numeric-data-type-1p6f</guid>
      <description>&lt;p&gt;&lt;a id="top"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;Table of Contents&lt;a id="toc-toogle"&gt;&lt;/a&gt;
&lt;/h3&gt;

&lt;dl&gt;
&lt;dt&gt;A. Introduction&lt;/dt&gt;
&lt;dt&gt;B. Numeric data type&lt;/dt&gt;
&lt;dt&gt;C. Integer&lt;/dt&gt;
&lt;dt&gt;D. Operators&lt;/dt&gt;

&lt;dd&gt;1. Arithmetic Operators&lt;/dd&gt;
&lt;dd&gt;2. Comparison operators&lt;/dd&gt;
&lt;dd&gt;3. Bitwise operators&lt;/dd&gt;

&lt;dt&gt;E. Class int() Constructor&lt;/dt&gt;
&lt;dt&gt;F. Built-in function bin()&lt;/dt&gt;
&lt;dt&gt;G. Integer Example Application&lt;/dt&gt;
&lt;dt&gt;H. Boolean&lt;/dt&gt;
&lt;dt&gt;
I. Class bool() Constructor&lt;dt&gt;

&lt;/dt&gt;
&lt;/dt&gt;
&lt;dd&gt;1. Boolean example 1&lt;/dd&gt;
&lt;dd&gt;2. Boolean example 2&lt;/dd&gt;
&lt;dd&gt;3. Boolean example 3&lt;/dd&gt;
&lt;dd&gt;4. Boolean example 4&lt;/dd&gt;

&lt;/dl&gt;

&lt;p&gt;&lt;a id="intro"&gt;&lt;/a&gt;&lt;br&gt;
&lt;h2&gt;A. Introduction&lt;/h2&gt;&lt;/p&gt;

&lt;p&gt;Data types are names given to an entity or object to differentiate them. The idea is to create a rule which operators to use for each specific type that allows Python to run efficiently. Programmers must also be familiar with the data types and operators. They need to know which data and operator to use in their program so that Python can execute them faster, lesser memory usage, and without errors.&lt;/p&gt;

&lt;p&gt;There are some data types in Python. We have integer, float, complex, bool, list, tuple, set, range, dictionary, string, and bytes. In this tutorial, I will only cover the integer and its subtype bool, they belong to the numeric type category.&lt;/p&gt;

&lt;p&gt;&lt;a id="numeric"&gt;&lt;/a&gt;&lt;br&gt;
&lt;h2&gt;B. Numeric data type&lt;/h2&gt;&lt;/p&gt;

&lt;p&gt;Numeric refers to numbers. Python has 5 numeric data types.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Integer
Float
Complex
Fraction
Decimal
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a id="int"&gt;&lt;/a&gt;&lt;br&gt;
&lt;h2&gt;C. Integer&lt;/h2&gt;&lt;/p&gt;

&lt;p&gt;Integers are numbers that are whole numbers. It can be a positive, negative and zero.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;100
-20
0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Python's integer maximum value is more than that of a &lt;a href="https://logiclair.org/1541/python-float-numeric-data-type"&gt;float&lt;/a&gt;. Note the maximum value of a float is 1.7976931348623157e+308.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; import sys
&amp;gt;&amp;gt;&amp;gt; int(sys.float_info.max)
179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You don't have to worry about overflow error then when processing huge integer values.&lt;/p&gt;

&lt;p&gt;&lt;a id="operator"&gt;&lt;/a&gt;&lt;br&gt;
&lt;h2&gt;D. Operators&lt;/h2&gt;&lt;/p&gt;

&lt;p&gt;Data needs an operator that will transform it to whatever the programmer wants. I will only cover some operators that are frequently used in integers.&lt;/p&gt;

&lt;p&gt;Arithmetic operators.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--W4rVhqSM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://user-images.githubusercontent.com/22366935/235307167-278d5297-7345-4ac2-aa11-5ff95eb8cbd6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--W4rVhqSM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://user-images.githubusercontent.com/22366935/235307167-278d5297-7345-4ac2-aa11-5ff95eb8cbd6.png" alt="image" width="288" height="272"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Comparison operators.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--clueyKPU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://user-images.githubusercontent.com/22366935/235307252-3079db57-31c2-49a2-bf62-9b8df99bddc1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--clueyKPU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://user-images.githubusercontent.com/22366935/235307252-3079db57-31c2-49a2-bf62-9b8df99bddc1.png" alt="image" width="277" height="266"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Bitwise operators.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Es0M5tv7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://user-images.githubusercontent.com/22366935/235307307-65d14e53-92f0-48e0-828a-44ec2875ccd4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Es0M5tv7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://user-images.githubusercontent.com/22366935/235307307-65d14e53-92f0-48e0-828a-44ec2875ccd4.png" alt="image" width="310" height="157"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Boolean operators.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--hs7-7URw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://user-images.githubusercontent.com/22366935/235307381-7f2798a3-49f5-482f-9328-ae1f6605e4af.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--hs7-7URw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://user-images.githubusercontent.com/22366935/235307381-7f2798a3-49f5-482f-9328-ae1f6605e4af.png" alt="image" width="495" height="159"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a id="arith"&gt;&lt;/a&gt;&lt;br&gt;
&lt;h3&gt;1. Arithmetic Operators&lt;/h3&gt;&lt;/p&gt;

&lt;p&gt;Addition and subtraction operators&lt;/p&gt;

&lt;p&gt;Start your Python interpreter from the terminal by typing python. It is assumed that you already installed Python on your computer.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;c:\&amp;gt;python
Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug  1 2022, 21:53:49) [MSC v.1932 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
&amp;gt;&amp;gt;&amp;gt; 10 + 2
12
&amp;gt;&amp;gt;&amp;gt; 10 - 6
4
&amp;gt;&amp;gt;&amp;gt; 20 - 0
20
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Multiplication and Division operators&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; 100 // 2
50
&amp;gt;&amp;gt;&amp;gt; 4*3
12
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the line "100//2", the "//" is called an integer division operator. Meaning it will return an integer value.&lt;/p&gt;

&lt;p&gt;Python has 2 division operators.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/
//
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The first will output a float data type while the second will output an integer. The latter will return the lowest whole number.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; 15 / 4
3.75
&amp;gt;&amp;gt;&amp;gt; 15 // 4
3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Remainder&lt;/p&gt;

&lt;p&gt;Python has an operator that can calculate the remainder. It is called the modulo operator with symbol "%".&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; 10 % 3
1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Power operator&lt;/p&gt;

&lt;p&gt;The built-in function pow() will return a number given base and exponent. It can also be expressed using double asterisk.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# a^b
&amp;gt;&amp;gt;&amp;gt; pow(2, 4)
16
&amp;gt;&amp;gt;&amp;gt; 2**4
16
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a id="compa"&gt;&lt;/a&gt;&lt;br&gt;
&lt;h3&gt;2. Comparison operators&lt;/h3&gt;&lt;/p&gt;

&lt;p&gt;Greater than operator "&amp;gt;".&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = 10
&amp;gt;&amp;gt;&amp;gt; b = 6
&amp;gt;&amp;gt;&amp;gt; if a &amp;gt; b:
...     print("a is greater than b")
... else:
...     print("a is not greater than b")
...
a is greater than b
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Greater than or equal to "&amp;gt;=".&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = 45
&amp;gt;&amp;gt;&amp;gt; b = 50
&amp;gt;&amp;gt;&amp;gt; a &amp;gt;= b
False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Not equal.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; 100 != 200
True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a id="bitwi"&gt;&lt;/a&gt;&lt;br&gt;
&lt;h3&gt;3. Bitwise operators&lt;/h3&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = 1
&amp;gt;&amp;gt;&amp;gt; b = 6
&amp;gt;&amp;gt;&amp;gt; a | b  # bitwise or
7
&amp;gt;&amp;gt;&amp;gt; a ^ b  # bitwise exclusive
7
&amp;gt;&amp;gt;&amp;gt; a &amp;amp; b  # bitwise and
0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a id="constructor"&gt;&lt;/a&gt;&lt;br&gt;
&lt;h2&gt;E. Class int() Constructor&lt;/h2&gt;&lt;/p&gt;

&lt;p&gt;Python has a built-in function called an int() or technically a class constructor that can set a different type into an integer type.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x_str = "8"
&amp;gt;&amp;gt;&amp;gt; type(x_str)
&amp;lt;class 'str'&amp;gt;
&amp;gt;&amp;gt;&amp;gt; x_str
'8'
&amp;gt;&amp;gt;&amp;gt; x_int = int(x_str)
&amp;gt;&amp;gt;&amp;gt; type(x_int)
&amp;lt;class 'int'&amp;gt;
&amp;gt;&amp;gt;&amp;gt; x_int
8
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;x_str is initially declared as a string data type.&lt;/li&gt;
&lt;li&gt;Get its type with another built-in function type(), and it is an str or string.&lt;/li&gt;
&lt;li&gt;Print the value.&lt;/li&gt;
&lt;li&gt;Convert it to an integer data type with the class constructor int().&lt;/li&gt;
&lt;li&gt;Get its type, and it is int .&lt;/li&gt;
&lt;li&gt;Print its value.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;span&gt;Tip&lt;/span&gt;&lt;br&gt;
&lt;span&gt;The built-in function type() returns the type of an object. Example, type(10) will return .&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;a id="builtin"&gt;&lt;/a&gt;&lt;br&gt;
&lt;h2&gt;F. Built-in function bin()&lt;/h2&gt;&lt;/p&gt;

&lt;p&gt;The function bin() converts an integer into a binary string format.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; num = 4
&amp;gt;&amp;gt;&amp;gt; num_binary = bin(num)
&amp;gt;&amp;gt;&amp;gt; print(num_binary)
'0b100'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The "0b" is a prefix to indicate that it is binary.&lt;/p&gt;

&lt;p&gt;We can remove the "0b" by splitting at "0b" and take the right side.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; type(num_binary)
&amp;lt;class 'str'&amp;gt;
&amp;gt;&amp;gt;&amp;gt; num_bin = num_binary.split("0b")[1]
&amp;gt;&amp;gt;&amp;gt; print(num_bin)
'100'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a id="intex"&gt;&lt;/a&gt;&lt;br&gt;
&lt;h2&gt;G. Integer Example Application&lt;/h2&gt;&lt;/p&gt;

&lt;p&gt;Let us create a python script to solve the example problem and use integer data type.&lt;/p&gt;

&lt;p&gt;Here is the problem: &lt;/p&gt;

&lt;p&gt;"You shop some fruits in the market. The fruits cost 55. Your money is 100. How much is your change?  Create a script that will ask the amount of money you have and the cost of fruits. Determine and print the change."&lt;/p&gt;

&lt;p&gt;Create a file "sample_1.py" and write the code on it.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;code&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Asks the amount of money you have.
my_money = input("How much money do you have? ")
my_money = int(my_money)

# Ask the cost of fruits.
fruit_cost = input("How much is the cost of fruits? ")
fruit_cost = int(fruit_cost)

# Use subtraction operator to get the difference.
change = my_money - fruit_cost
print("change: " + str(change))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The line that starts with "#" is just a comment and will not be executed by python.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;execute the code&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;c:\&amp;gt;python sample_1.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The "sample_1.py" must be in "C" drive for this particular example.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;output&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;How much money do you have? 100
How much is the cost of fruits? 55
change: 45
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a id="bool"&gt;&lt;/a&gt;&lt;br&gt;
&lt;h2&gt;H. Boolean&lt;/h2&gt;&lt;/p&gt;

&lt;p&gt;Boolean or bool data type is a subset of Integer. This type can have 2 values, either True or False. Technically it is just 1 or 0.&lt;/p&gt;

&lt;p&gt;&lt;a id="boolcons"&gt;&lt;/a&gt;&lt;br&gt;
&lt;h2&gt;I. Class bool() Constructor&lt;/h2&gt;&lt;/p&gt;

&lt;p&gt;Python has a built-in function called a bool() or technically a class constructor that can set a different type into a bool type.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = 45
&amp;gt;&amp;gt;&amp;gt; type(a)
&amp;lt;class 'int'&amp;gt;
&amp;gt;&amp;gt;&amp;gt; a_bool = bool(a)
&amp;gt;&amp;gt;&amp;gt; a_bool
True
&amp;gt;&amp;gt;&amp;gt; type(a_bool)
&amp;lt;class 'bool'&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We use bool() to convert an integer 45 to bool type.&lt;/p&gt;

&lt;p&gt;&lt;a id="bool-1"&gt;&lt;/a&gt;&lt;br&gt;
&lt;h3&gt;1. Boolean example 1&lt;/h3&gt;&lt;/p&gt;

&lt;p&gt;Boolean is usually used in if conditions.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; is_raining = True
&amp;gt;&amp;gt;&amp;gt; if is_raining:
...     print("It is raining.")
... else:
...     print("It is not raining.")
...
It is raining.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a id="bool-2"&gt;&lt;/a&gt;&lt;br&gt;
&lt;h3&gt;2. Boolean example 2&lt;/h3&gt;&lt;/p&gt;

&lt;p&gt;The "or" operator is acting on the bool type. &lt;/p&gt;

&lt;p&gt;We have a buy and not buy situations. We buy the vegetable if it is fresh. However if it is not fresh, we will still buy it if it is cheap.&lt;/p&gt;

&lt;p&gt;Given:  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The vegetable is not fresh.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The vegetable is cheap.&lt;/p&gt;

&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;is_vegetable_fresh = False&lt;br&gt;
is_vegetable_cheap = True&lt;br&gt;
if is_vegetable_fresh or is_vegetable_cheap:&lt;br&gt;
...     print("Buy it.")&lt;br&gt;
... else:&lt;br&gt;
...     print("Don't buy it.")&lt;br&gt;
...&lt;br&gt;
Buy it.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;/blockquote&gt;
&lt;/blockquote&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The first test is "is_vegetable_fresh", since its value is False, we will test the next condition. The "or" will test every conditions until the value is True.&lt;/p&gt;

&lt;p&gt;&lt;a id="bool-3"&gt;&lt;/a&gt;&lt;br&gt;
&lt;h3&gt;3. Boolean example 3&lt;/h3&gt;&lt;/p&gt;

&lt;p&gt;The "and" operator is acting on the bool type.&lt;/p&gt;

&lt;p&gt;Here is an example conditions. We will go outside if it is not raining and the temperature is not hot.&lt;/p&gt;

&lt;p&gt;Given:  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It is not raining.
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The temperature is not hot.&lt;/p&gt;

&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;is_not_raining = True&lt;br&gt;
is_temperature_not_hot = True&lt;br&gt;
if is_not_raining and is_temperature_not_hot:&lt;br&gt;
...     print("go outside")&lt;br&gt;
... else:&lt;br&gt;
...     print("do not go outside")&lt;br&gt;
...&lt;br&gt;
go outside&lt;/p&gt;
&lt;/blockquote&gt;
&lt;/blockquote&gt;
&lt;/blockquote&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The "go outside" is printed because the two conditions are both True.&lt;/p&gt;

&lt;p&gt;&lt;a id="bool-4"&gt;&lt;/a&gt;&lt;br&gt;
&lt;h3&gt;4. Boolean example 4&lt;/h3&gt;&lt;/p&gt;

&lt;p&gt;Here is an example "not" operator acting on the bool type. We will use "not" to convert the value to the opposite value.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; is_good = True
&amp;gt;&amp;gt;&amp;gt; is_good = not is_good
&amp;gt;&amp;gt;&amp;gt; print(is_good)
False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The "is_good" is initialized to True. To make it False, we use "not is_good".&lt;/p&gt;

</description>
      <category>python</category>
    </item>
    <item>
      <title>Date format dd-mm-yyyy in C</title>
      <dc:creator>AnkurRanpariya2005</dc:creator>
      <pubDate>Mon, 29 May 2023 10:11:36 +0000</pubDate>
      <link>https://forem.com/ankurranpariya2005/date-format-dd-mm-yyyy-in-c-2e67</link>
      <guid>https://forem.com/ankurranpariya2005/date-format-dd-mm-yyyy-in-c-2e67</guid>
      <description>&lt;p&gt;When working with &lt;strong&gt;dates in C&lt;/strong&gt;, it's essential to understand the date system, date format, and how C handles dates. One common date format is &lt;strong&gt;dd-mm-yyyy&lt;/strong&gt;, which represents the day, month, and year separated by hyphens. Converting a date to this format can be necessary for data processing or display purposes. In this article, we'll explore different ways to convert a &lt;strong&gt;date to dd-mm-yyyy format in C&lt;/strong&gt;. Whether you prefer using built-in functions or custom solutions, I've got you covered. So let's dive in!&lt;/p&gt;

&lt;h2&gt;&lt;span&gt;&lt;strong&gt;Date in C&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;

&lt;p&gt;Dates are an essential aspect of programming, and handling them correctly is crucial for any program that relies on time-based functionality. In C, dates are typically stored as integers, with each digit representing a specific aspect of the date, such as day, month, and year.&lt;/p&gt;

&lt;h3&gt;&lt;span&gt;&lt;strong&gt;Date system&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;

&lt;p&gt;The date system used in C is based on the Unix timestamp, which is the number of seconds that have elapsed since January 1, 1970, at 00:00:00 UTC. This system is also known as POSIX time or Unix epoch time. It is a widely used standard for representing dates and times in programming languages, operating systems, and other software applications.&lt;/p&gt;

&lt;h3&gt;&lt;span&gt;&lt;strong&gt;How C handles date?&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;

&lt;p&gt;In C, the date and time functions are provided by the standard library "time.h." This library contains a set of functions that allow you to manipulate dates and times in various formats. Some of the most commonly used functions include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;time()&lt;/strong&gt;: returns the current time as the number of seconds since the Unix epoch.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;localtime()&lt;/strong&gt;: converts a time_t value to a tm structure, which contains information about the local time, such as year, month, day, hour, minute, and second.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;strftime()&lt;/strong&gt;: formats a tm structure into a string representation of the date and time, using a specific format specifier.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Remember these functions, we will come back to them later. &lt;/p&gt;

&lt;h2&gt;&lt;span&gt;&lt;strong&gt;How to convert date to format dd-mm-yyyy?&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;

&lt;p&gt;The default date format used in C is not dd-mm-yyyy, but rather yyyy-mm-dd. This format is also known as ISO 8601 and is widely used in international contexts. However, you will often need to convert dates to other formats, such as dd-mm-yyyy, to meet specific requirements. Fortunately, there are several ways to accomplish this task.&lt;/p&gt;

&lt;h3&gt;&lt;span&gt;&lt;strong&gt;Solution 1: Using sprintf() &lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;

&lt;p&gt;One way to convert a date to dd-mm-yyyy format is to use the &lt;strong&gt;sprintf()&lt;/strong&gt; function, which allows you to format a string just like 'printf()'. Here's an example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include 
#include 

int main() {
   time_t now;
   struct tm *local;
   char date_str[11];

   now = time(NULL);
   local = localtime(&amp;amp;now);

   sprintf(date_str, "%02d-%02d-%04d", local-&amp;gt;tm_mday, local-&amp;gt;tm_mon + 1, local-&amp;gt;tm_year + 1900);

   printf("Date: %s\n", date_str);

   return 0;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can see we are using time_t and struct tm type in our code:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;time_t is a data type defined in the  header file in C. It represents time in seconds since the Unix epoch (January 1, 1970, 00:00:00 UTC)&lt;/li&gt;
&lt;li&gt;struct tm is a structure defined in the same  header, contains fields for the various components of calendar date and time, such as the year, month, day, hour, minute, and second.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now let's take a look at these two lines of code:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;now = time(NULL) gets the current time in seconds since the Unix epoch and stores it in the now variable of type 'time_t'. The NULL argument tells the 'time()' function to use the current time.&lt;/li&gt;
&lt;li&gt;local = localtime(&amp;amp;now) takes the 'time_t' value stored in now and converts it into a 'struct tm' value representing the local time.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Then, we are formatting the date string in the &lt;strong&gt;date_str&lt;/strong&gt; array, by accessing values of the date through &lt;strong&gt;local&lt;/strong&gt; variable. The &lt;strong&gt;%02d&lt;/strong&gt; specifier ensures that the day and month are zero-padded to two digits, and the &lt;strong&gt;%04d&lt;/strong&gt; specifier ensures that the year is zero-padded to four digits. We add 1 to the month value (since January is 0) and 1900 to the year value (since the 'tm_year field' is the number of years since 1900).&lt;/p&gt;

&lt;h3&gt;&lt;span&gt;&lt;strong&gt;Solution 2: Using strftime()&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;

&lt;p&gt;You can also use the &lt;strong&gt;strftime()&lt;/strong&gt; function to achieve similar result. We use the same code as in solution 1 but replace one line only:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;//sprintf(date_str, "%02d-%02d-%04d", local-&amp;gt;tm_mday, local-&amp;gt;tm_mon + 1, local-&amp;gt;tm_year + 1900);
strftime(date_str, sizeof(date_str), "%d-%m-%Y", local);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The "%d-%m-%Y" format specifier produces the same result as the "%02d-%02d-%04d" specifier used in the previous example.&lt;/p&gt;

&lt;h3&gt;&lt;span&gt;&lt;strong&gt;Solution 3: Extended custom function&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;

&lt;p&gt;Let's write a custom function that performs the conversion:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;void date_to_string(char *str, const struct tm *timeptr) {
   sprintf(str, "%02d-%02d-%04d", timeptr-&amp;gt;tm_mday, timeptr-&amp;gt;tm_mon + 1, timeptr-&amp;gt;tm_year + 1900);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;strong&gt;date_to_string()&lt;/strong&gt; function takes a pointer to a 'tm' structure and a pointer to a character array. You can call and pass it the local time pointer and the date string array. But the content inside the function is the same as solution 1, using sprintf() to format the date as a string in dd-mm-yyy format.&lt;/p&gt;

&lt;p&gt;We can improve our custom function by using a lookup table for month abbreviations. This can be useful if you need to perform the conversion frequently or want to avoid the overhead of formatting the date using sprintf() or other functions:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;const char *months[] = {
   "", "Jan", "Feb", "Mar", "Apr", "May", "Jun",
   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Or if you don't like to use the hyphen symbol '-' between day, month, and year. No problem, you can adjust the code to allow for different date separators.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/*Multiple type of separators
dd/mm/yyyy
dd.mm.yyyy
dd|mm|yyyy
*/&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here's an example of extended version of the 'date_to_string' function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include 
#include 

void date_to_string(int day, int month, int year, char *str, const char *separator) {
   const char *month_abbr[] = {"", "Jan", "Feb", "Mar", "Apr", "May", "Jun",
      "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
   char month_str[4];
   sprintf(month_str, "%s", month_abbr[month]);

   char day_str[3];
   sprintf(day_str, "%02d", day);

   char year_str[5];
   sprintf(year_str, "%04d", year);

   strcpy(str, day_str);
   strcat(str, separator);
   strcat(str, month_str);
   strcat(str, separator);
   strcat(str, year_str);
}

int main() {
   int day, month, year;
   char date_str[11];

   // Prompt the user for the date
   printf("Enter the date (dd-mm-yyyy): ");
   scanf("%d-%d-%d", &amp;amp;day, &amp;amp;month, &amp;amp;year);

   // Format the date using a custom function
   date_to_string(day, month, year, date_str, "-");

   printf("Date: %s\n", date_str);

   return 0;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this example, we've extended the date_to_string() function to include a custom separator as an argument. We've also used a custom implementation for the month abbreviation, which we store in an array of string literals. We then use sprintf() to format the day, month, and year as strings and concatenate them with the separator character.&lt;/p&gt;

&lt;p&gt;This extended date_to_string() function allows for greater customization of the output format, making it a versatile and flexible solution for date formatting in C.&lt;/p&gt;



&lt;h2&gt;&lt;span&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;

&lt;p&gt;This article has covered various aspects of working with dates in C, including the date system, date format, and how C handles dates. Additionally, we have explored multiple solutions for &lt;strong&gt;converting dates to the dd-mm-yyyy format&lt;/strong&gt;, which can be useful for displaying dates in a user-friendly manner or performing date arithmetic. By understanding the techniques presented in this article, you as a C programmer can effectively work with dates in your programs.&lt;/p&gt;

</description>
      <category>c</category>
    </item>
    <item>
      <title>"Expected declaration or statement at end of input" in C [Solved]</title>
      <dc:creator>AnkurRanpariya2005</dc:creator>
      <pubDate>Fri, 26 May 2023 15:30:14 +0000</pubDate>
      <link>https://forem.com/ankurranpariya2005/expected-declaration-or-statement-at-end-of-input-in-c-solved-4fa4</link>
      <guid>https://forem.com/ankurranpariya2005/expected-declaration-or-statement-at-end-of-input-in-c-solved-4fa4</guid>
      <description>&lt;p&gt;Programming in C requires careful attention to detail, as even small syntax errors can cause unexpected problems in your code. One common error message that developers may encounter when writing C code is "Expected declaration or statement at end of input." This error message can be frustrating to deal with, but fortunately, it is usually straightforward to diagnose and fix. In this article, you will learn how to identify where the problem is, how to deal with it, and how to avoid it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Identify the problem
&lt;/h2&gt;

&lt;p&gt;When the "Expected declaration or statement at end of input" error occurs, it means that the compiler has reached the end of the file or function without finding a complete statement or declaration. In other words, the compiler is expecting to find some additional code but instead has reached the end of the program without finding it.&lt;/p&gt;

&lt;p&gt;Identifying the problem that caused the error can be tricky, but it usually comes down to a missing bracket, semicolon, or parenthesis in your code. In order to fix the error, you need to determine exactly what is missing and where it needs to be added. This can involve carefully reviewing your code line by line to find the missing expression.&lt;/p&gt;

&lt;p&gt;In the next section, we will explore some common examples of what can cause this error and how to resolve them.&lt;/p&gt;

&lt;h2&gt;
  
  
  Examples and solutions
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Missing Semicolon
&lt;/h3&gt;

&lt;p&gt;One common cause of the error is a missing semicolon at the end of a line of code. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int main() {
  printf("Hello, World!")
  return 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the error message will indicate that the problem is on line 2, where there is a missing semicolon after the printf() statement. To fix the error, you simply need to add the semicolon.&lt;/p&gt;

&lt;h3&gt;
  
  
  Missing Bracket
&lt;/h3&gt;

&lt;p&gt;Another cause of the error is a missing bracket after a function call. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include 

int sum(int x, int y) {
  return x + y;
//missing closing bracket

int main() {
  int result = sum(3, 4);
  printf("The result is %d\n", result);
  return 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, the error message still indicate there is an error, but might not point out exactly where the problem is. To fix the error, you need to review carefully each line, especially in the non-main function.&lt;/p&gt;

&lt;h3&gt;
  
  
  Missing Parenthesis
&lt;/h3&gt;

&lt;p&gt;A missing parenthesis, whether in the condition after the if-else statement or in a function call, can also cause this type of error. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int main() {
  int x = 5;
  if (x &amp;lt; 10 
    printf("x is less than 10\n");

  return 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Unless the message error shows you where the problem lies, review your code carefully, and add the missing parenthesis where the place is needed.&lt;/p&gt;

&lt;h3&gt;
  
  
  Other examples
&lt;/h3&gt;

&lt;p&gt;This type of error can easily be caused by syntax errors, mainly from the developers themself. You can see some examples below:&lt;/p&gt;

&lt;p&gt;Unclosed Quotes&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int main() {
  printf("Hello, World!); //Missing double quotation marks
  return 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Mismatched bracket&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int main() {
    printf("Hello, world!\n");
        if (1) {
            printf("This statement will execute.\n"); //Missing closing bracket
        else { 
            printf("This statement will not execute.\n");
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Depending on your compiler and IDE, the error message for the "expected declaration or statement at end of input" error may vary. However, in most cases, the error message will specifically point out what the missing expression is. Regardless of the specific error message, the cause of the problem is still a syntax error in your code. Therefore, it's important to carefully check your code for any missing expressions and practice good coding habits to prevent these types of errors. You can learn it in the next section.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to prevent
&lt;/h2&gt;

&lt;p&gt;Syntax errors like "expected declaration or statement at end of input" can be prevented with good coding practices. Here are some tips to prevent this error from happening:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Always ensure that every loop and function has an opening and a closing bracket.&lt;/li&gt;
&lt;li&gt;At the end of every command line, there should be a semicolon.&lt;/li&gt;
&lt;li&gt;Wrap every conditional statement in parentheses.&lt;/li&gt;
&lt;li&gt;Every time a function is declared or called, its parameters/arguments should be wrapped in opening and closing parentheses.&lt;/li&gt;
&lt;li&gt;Practice indentation: Proper indentation makes the code more readable and easier to understand. It also helps in identifying syntax errors, including the "expected declaration or statement at end of input" error.&lt;/li&gt;
&lt;li&gt;Use an IDE with syntax highlighting.&lt;/li&gt;
&lt;li&gt;Use an online compiler: similar to a modern IDE, online compilers can be useful for identifying syntax errors. They often highlight syntax errors and provide error messages that can help programmers fix the errors.&lt;/li&gt;
&lt;li&gt;Run your code through a code formatter like "indent": This is especially useful for large codebases where it can be difficult to identify syntax errors by hand. Here's a brief guide on how to install indent on Ubuntu:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Open the terminal and run the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sudo apt-get update
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After the update completes, install the indent package using the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sudo apt-get install indent
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once the installation is complete, you can use the "indent" command to format your C code. Simply navigate to the directory containing your C code file and run this command in the terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;indent .c
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, open your file in text editor and verify that the code is now formatted correctly.&lt;br&gt;
By following these tips, you can nearly prevent any syntax errors in your code. Last but not least, remember to always double-check the code for errors before compiling it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this article, we have learned that the "expected declaration or statement at end of input" error is a common error in C programming that can be caused by missing braces, semicolons, or parentheses in our code. To prevent this error, it's important to practice good coding habits such as always ensuring loops and functions have opening and closing brackets, using semicolons at the end of each command line, and wrapping every conditional statement with parentheses. If you encounter this error, check your code for missing expressions and use an online compiler or code formatter to help identify the issue. By following these practices and using the appropriate tools, you can write more robust and error-free C code.&lt;/p&gt;

&lt;p&gt;That's all for now. Happy coding!&lt;/p&gt;

</description>
      <category>c</category>
    </item>
    <item>
      <title>How to use OpenAI's ChatGPT API</title>
      <dc:creator>AnkurRanpariya2005</dc:creator>
      <pubDate>Thu, 25 May 2023 12:38:20 +0000</pubDate>
      <link>https://forem.com/ankurranpariya2005/how-to-use-openais-chatgpt-api-4j7p</link>
      <guid>https://forem.com/ankurranpariya2005/how-to-use-openais-chatgpt-api-4j7p</guid>
      <description>&lt;h2&gt;
  
  
  A. What is OpenAI and ChatGPT
&lt;/h2&gt;

&lt;p&gt;OpenAI is an AI research and deployment company founded in December 2015. It is responsible for building the GPT-3 large language model (LLM) which is trained from a huge text dataset from internet. This model may generate "untruthful, toxic, or reflect harmful sentiments" - OpenAI. A new model called InstructGPT was created to address these shortcomings. This model is fine-tuned from GPT-3, to follow instructions using human feedback.&lt;/p&gt;

&lt;p&gt;"ChatGPT is similar to InstructGPT but with slight differences in the data collection setup" - OpenAI. ChatGPT can generate text responses based from the text input from the users. It is optimized for chatbots application and communication interfaces. The model was trained using Reinforcement Learning with Human Feedback (RLHF). Based on ChatGPT release notes as of January 30 2023 from &lt;a href="https://help.openai.com/en/articles/6825453-chatgpt-release-notes"&gt;https://help.openai.com/en/articles/6825453-chatgpt-release-notes&lt;/a&gt;, the model has been improved on factuality and mathematical capabilities. Historically, ChatGPT is fined-tuned from OpenAI's GPT-3.5 language model. GPT stands for Generative Pre-trained Transformer.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Structure
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--VVEU3tHk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lsycep7e46speb6xx0si.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--VVEU3tHk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lsycep7e46speb6xx0si.png" alt="Image description" width="800" height="505"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Usage of GPT-3
&lt;/h3&gt;

&lt;p&gt;According to OpenAI, you can build your own applications with GPT-3.5-turbo (the latest model so far) to do things such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Draft an email or other piece of writing&lt;/li&gt;
&lt;li&gt;Write Python code&lt;/li&gt;
&lt;li&gt;Answer questions about a set of documents&lt;/li&gt;
&lt;li&gt;Create conversational agents&lt;/li&gt;
&lt;li&gt;Give your software a natural language interface&lt;/li&gt;
&lt;li&gt;Tutor in a range of subjects&lt;/li&gt;
&lt;li&gt;Translate languages&lt;/li&gt;
&lt;li&gt;Simulate characters for video games and much more
##B. User Registration
The ChatGPT can only be used by a registered user. You can register at &lt;a href="https://platform.openai.com/signup"&gt;https://platform.openai.com/signup&lt;/a&gt;. After the registration you will receive 18.0 USD which you can use to explore OpenAI's services and model use. You are now in a category as Free Trial Users.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  1. Login / signup
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--W_-3dtZr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ki3zlmksf8pymgd2hlb3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--W_-3dtZr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ki3zlmksf8pymgd2hlb3.png" alt="Image description" width="348" height="487"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  2. API Key Access
&lt;/h3&gt;

&lt;p&gt;After the log in, press at the top right menu to access other menu items including the View API keys to generate secret api keys.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Z8QXly5m--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jhqclv7sadswmlyevjjq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Z8QXly5m--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jhqclv7sadswmlyevjjq.png" alt="Image description" width="400" height="396"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  C. Create new key
&lt;/h3&gt;

&lt;p&gt;The keys are used by OpenAI to authenticate their users.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--22eJ0YvI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/51rn49i0mm7i1d8jtjc1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--22eJ0YvI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/51rn49i0mm7i1d8jtjc1.png" alt="Image description" width="774" height="344"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  D. ChatGPT Research Preview
&lt;/h2&gt;

&lt;p&gt;It is a service provided by OpenAI that is free of charge. It has some limitations such as number of requests per minute and number of tokens per minute. This will allow users to explore the ChatGPT capabilties such as asking questions and get back responses. In return, OpenAI can further improve ChatGPT based from these questions and responses.&lt;/p&gt;

&lt;p&gt;You can access the ChatGPT Research Preview from &lt;a href="https://chat.openai.com/chat"&gt;https://chat.openai.com/chat&lt;/a&gt;. You will be required to log in with your credentials.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Example dialogue
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--4-pySpVk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xiwkpan5ja453tndw4ya.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--4-pySpVk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xiwkpan5ja453tndw4ya.png" alt="Image description" width="787" height="555"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  E. ChatGPT API
&lt;/h2&gt;

&lt;p&gt;OpenAI had recently released ChatGPT API. API is an acronym for Application Programming Interface. It provides a means for the developers to integrate ChatGPT on their applications or even create a new application solely based from ChatGPT.&lt;/p&gt;

&lt;p&gt;There are 2 ways to use the API in Python, first is by using the OpenAI python library and second is by using the OpenAI Endpoint.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. OpenAI Python Library
&lt;/h3&gt;

&lt;p&gt;Openai has a python package at &lt;a href="https://pypi.org/project/openai/"&gt;https://pypi.org/project/openai/&lt;/a&gt; for openai API, ChatGPT API and DALL.E API. I will create sample code on how to use it for ChatGPT.&lt;/p&gt;

&lt;p&gt;main.py&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import openai

openai.api_key = "your-api-key"
messages = [{"role": "user", "content": "Hello, how are you?"}]

response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    temperature=1.0,
    top_p=1.0,
    n=1,
    presence_penalty=0.0,
    frequency_penalty=0.0,
    max_tokens=150,
    messages=messages
)
print(response)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run the script with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python main.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "choices": [
    {
      "finish_reason": null,
      "index": 0,
      "message": {
        "content": "\n\nAs an AI language model, I don't have feelings, but I'm functioning perfectly fine. Thank you for asking. How can I assist you?",
        "role": "assistant"
      }
    }
  ],
  "created": 1678283150,
  "id": "chatcmpl-6roP0H4URtFW8G4MQgYa7UunULCvT",
  "model": "gpt-3.5-turbo-0301",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 32,
    "prompt_tokens": 11,
    "total_tokens": 43
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output is like a python dictionary or a json format. We can get the content through the keys.&lt;/p&gt;

&lt;p&gt;main.py&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;reply_content = response["choices"][0]["message"]["content"]
print(reply_content)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;reply_content&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;As an AI language model, I do not have emotions in the human sense, but I am functioning well and ready to assist you with any inquiries you may have. How can I assist you today?
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;full code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import openai  # OpenAI Python v0.27.0

openai.api_key = "your api key"
messages = [{"role": "user", "content": "Hello, how are you?"}]

response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    temperature=1.0,
    top_p=1.0,
    n=1,
    presence_penalty=0.0,
    frequency_penalty=0.0,
    max_tokens=150,
    messages=messages
)

print(response)

reply_content = response["choices"][0]["message"]["content"]
print(reply_content)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Chat Completion Parameters&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;model: ID of the model to use.  
message: The messages to generate chat completions for
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;See also the complete parameter definitions at &lt;a href="https://platform.openai.com/docs/api-reference/chat"&gt;https://platform.openai.com/docs/api-reference/chat&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. OpenAI Endpoint
&lt;/h3&gt;

&lt;p&gt;The second method does not need the OpenAI python package. But it needs a requests package to make a post request to the endpoint.&lt;/p&gt;

&lt;p&gt;full code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"""
requirements.txt
    requests
"""

import requests
import json

# Set the API endpoint URL
url = "https://api.openai.com/v1/chat/completions"

# Set your API key
api_key = "your-api-key"

# Set the headers for the HTTP request
headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {api_key}"
}

# Our message is a list of dictionaries.
messages = []

system_message = {"role": "system", "content": "Be creative and expressive."}
messages.append(system_message)

user_message = {"role": "user",
                "content": "Could you suggest a best approach to study react programming."}
messages.append(user_message)

# Set the payload data for the HTTP request
model = "gpt-3.5-turbo-0301"
data = {
    "model": model,
    "messages": messages,
    "temperature": 1.0,
    "top_p": 1.0,
    "n": 1,
    "stream": False,
    "presence_penalty": 0,
    "frequency_penalty": 0,
    "max_tokens": 256
}

# Send the HTTP request using the requests library
response = requests.post(url, headers=headers, data=json.dumps(data))

# Read request response.
if response.status_code == 200:
    json_response = response.json()
    reply_content = json_response["choices"][0]["message"]["content"]
    reply_usage = json_response["usage"]["total_tokens"]

    print("messages: " + str(messages))
    print("response: " + json.dumps(json_response, indent=4))
    print("tokens: " + str(reply_usage))
    print("content: " + reply_content)
else:
    print(f"Error: {response.json()['error']['message']}")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;messages: [{'role': 'system', 'content': 'Be creative and expressive.'}, {'role': 'user', 'content': 'Could you suggest a best approach to study react programming.'}]
response: {
    "id": "chatcmpl-6uOlfMlkY7jfcce7XpqM4EpQG7gTS",
    "object": "chat.completion",
    "created": 1678899595,
    "model": "gpt-3.5-turbo-0301",
    "usage": {
        "prompt_tokens": 28,
        "completion_tokens": 256,
        "total_tokens": 284
    },
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "\n\nSure, I would suggest the following approach for studying React programming:\n\n1. Learn the fundamentals of JavaScript - React is built on top of JavaScript, so having a solid understanding of JavaScript is essential. You can refer to online tutorials, courses, and books to learn JavaScript.\n\n2. Learn the basics of React - Start with the official website of React which provides high-quality documentation, tutorials, and example code to learn the basics of React. You can also consult reliable online resources such as tutorialspoint, reactjs.org to learn React in-depth.\n\n3. Build simple projects - After learning the fundamentals of React, start building simple projects to experiment and implement your learnings. This helps in mastering the basics of React and gives hands-on experience in solving real-world problems.\n\n4. Follow best practices - As you start building complex projects, it's important to follow best practices such as using reusable components, modularizing code, designing a clean and scalable architecture, and writing clean and readable code.\n\n5. Keep practicing - Keep building projects and experimenting with different React features and concepts to hone your skills. Participate in online React communities, attend meetups, and ask questions to learn from experts in the field.\n\nRemember, 
the key to mastering React programming is to keep practicing and experimenting with"
            },
            "finish_reason": "length",
            "index": 0
        }
    ]
}
tokens: 284
content:

Sure, I would suggest the following approach for studying React programming:

1. Learn the fundamentals of JavaScript - React is built on top of JavaScript, so having a solid understanding of JavaScript is essential. You can refer to online tutorials, courses, and books to learn JavaScript.

2. Learn the basics of React - Start with the official website of React which provides high-quality documentation, tutorials, and example code to learn the basics of React. You can also consult reliable online resources such as tutorialspoint, reactjs.org to learn React in-depth.

3. Build simple projects - After learning the fundamentals of React, start building simple projects to experiment and implement your learnings. This helps in mastering the basics of React and gives hands-on experience in solving real-world problems.

4. Follow best practices - As you start building complex projects, it's important to follow best practices such as using reusable components, modularizing code, designing a clean and scalable architecture, and writing clean and readable code.

5. Keep practicing - Keep building projects and experimenting with different React features and concepts to hone your skills. Participate in online React communities, attend meetups, and ask questions to learn from experts in the field.

Remember, the key to mastering React programming is to keep practicing and experimenting

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  F. Summary
&lt;/h2&gt;

&lt;p&gt;We got a basic knowledge of what OpenAI is and what the company has been developing. We also knew how to use the ChatGPT API to send our message or prompt and get back the model's response with the use of OpenAI's library package and Chat endpoint. This service is not free but OpenAI gives 18 usd so that users can explore ChatGPT API. This amount can also be used in exploring other models.&lt;/p&gt;

&lt;p&gt;As of March 14, 2023, GPT-4 was released with enhanced capabilities such as Advanced reasoning, Complex instructions, and More creativity according to OpenAI.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How to send Discord Embeds without Bots + Rules Template</title>
      <dc:creator>AnkurRanpariya2005</dc:creator>
      <pubDate>Wed, 24 May 2023 16:44:53 +0000</pubDate>
      <link>https://forem.com/ankurranpariya2005/how-to-send-discord-embeds-without-bots-rules-template-4e46</link>
      <guid>https://forem.com/ankurranpariya2005/how-to-send-discord-embeds-without-bots-rules-template-4e46</guid>
      <description>&lt;p&gt;Wouldn't you like your discord server to stand out from the crowd? Read the tutorial all the way through to learn how to create the most beautiful Discord server.&lt;/p&gt;

&lt;p&gt;Discord Embeds are customized messages that contain information and/or media added by the user. They can include text, images, videos, and more. Embeds are a great way to enhance the user experience on Discord and make messages stand out.&lt;/p&gt;

&lt;p&gt;To be able to send an embedded message, we need to learn how to create Discord Webhooks. After learning how to create a Webhook, we need to learn how to create an Embed for the Webhook, this is where discohook.org comes in.&lt;/p&gt;

&lt;h2&gt;
  
  
  Things to learn from this article
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;What are Discord Webhooks&lt;/li&gt;
&lt;li&gt;How to use Discord Webhooks&lt;/li&gt;
&lt;li&gt;How to send Discord Embeds using Discohook&lt;/li&gt;
&lt;li&gt;Rules Template + Designs
##1. How to create Discord Webhooks?
Discord Webhooks are a component of Discord servers. Thus, every webhook is scoped to a particular server and is connected to a channel that resides on that server. This helps you to organize your webhooks based on their purpose.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;To find the webhooks that belong to a server, go to the Server Settings page by clicking the down arrow beside the server name to open the server's context menu, as shown below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkcdz0nyx1tyr435zy1n2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkcdz0nyx1tyr435zy1n2.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Click Server Settings and go to Integrations on the side menu. There, you can see your webhooks and create new webhooks.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. How to use Discord Webhooks?
&lt;/h2&gt;

&lt;p&gt;To add a webhook to your Discord server, follow the steps listed below:&lt;br&gt;
Go to the Integrations page on your Discord server as described above and click Create Webhook&lt;br&gt;
Give your webhook a descriptive name and select the channel you want your messages to be sent to&lt;br&gt;
Remember to click Save Changes when you make any change to your webhook configuration&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhc3bimvdyprervn8fcwy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhc3bimvdyprervn8fcwy.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;That's all! You now have a webhook added to your server in order to send messages to the channel you have selected. Click Copy Webhook URL to get your webhook URL and use it to send messages from external applications into your Discord channel.&lt;/p&gt;
&lt;h2&gt;
  
  
  3. How to send Discord Embeds using Discohook?
&lt;/h2&gt;

&lt;p&gt;Discohook is a free tool that allows you to personalize your server to make your server stand out from the crowd. The main way it does this is using webhooks, which allows services like Discohook to send any messages with embeds to your server.&lt;/p&gt;

&lt;p&gt;How do I send embeds using Discohook?&lt;br&gt;
To send Embed Messages you need to go to &lt;a href="https://discohook.org" rel="noopener noreferrer"&gt;https://discohook.org&lt;/a&gt;, then start editing all the fields until you get to a design you like.&lt;/p&gt;
&lt;h2&gt;
  
  
  4. Rules Template + Design Link
&lt;/h2&gt;

&lt;p&gt;To import a design, enter discohook.org, click Backups and then Import.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Template 1&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "version": 7,
  "backups": [
    {
      "name": "OpenAI",
      "messages": [
        {
          "data": {
            "content": null,
            "embeds": [
              {
                "title": "`  Rule 1  `   Be respectful; keep negativity to a minimum.",
                "description": "Treat everyone how you would like to be treated. Do not directly swear or make rude comments to other users, starting unnecessary fights and drama will not be tolerated here. Civil debates are allowed to an extent however creating fights that will lead to nowhere will result in a punishment.",
                "color": 3224376
              },
              {
                "title": "`  Rule 2  `   No Inappropriate/NSFW content",
                "description": "Keep things appropriate for everyone. Sending NSFW content, such as messages, media or overall sexual behavior will result in serious consequences. Having inappropriate remarks in your public profile will also result in a ban.",
                "color": 3224376
              },
              {
                "title": "`  Rule 3  `   No Profane Language",
                "description": "Simple swearing (e.g. f*** or s***) is allowed to a certain extent (refer to rule 1) but using extreme slurs that are racist, homophobic, transphobic or discrimination at all will result in a permanent ban.",
                "color": 3224376
              },
              {
                "title": "`  Rule 4  `   No Spamming",
                "description": "Spamming can mean many things, examples are sending many messages within a short period of time, sending text walls (messages that take space on a lot of the screen), chaining lyrics, sending attachments repetitively etc. Making the overall experience in the chat bad can also be considered spam.",
                "color": 3224376
              },
              {
                "title": "`  Rule 5  `   No Mini-modding",
                "description": "If something needs to be moderated, leave it to the staff. Don't moderate the server or give out false information to users. If you think something needs to be taken care of, ping an active staff member or report the issue in #support-tickets.",
                "color": 3224376
              },
              {
                "title": "`  Rule 6  `   Begging",
                "description": "Do not ask for free Nitro, Roles, Bot currency or anything else. We don't randomly hand out things for free excluding giveaways. Do not ask for free stuff, continuing will result in a punishment.",
                "color": 3224376
              },
              {
                "title": "`  Rule 7  `   Terms of Service",
                "description": "Abide by the Discord's Terms of Service and Community Guidelines. Not following to do so may result in a ban from the server.",
                "color": 3224376
              },
              {
                "title": "`  Rule 8  `   Wasting Staff's Time",
                "description": "Do not waste staff's time, this can include direct messaging staff to appeal your punishment, opening tickets for no reason, or annoying them in general. If you have a complaint against a higher staff member, contact a higher position staff.",
                "color": 3224376
              },
              {
                "title": "`  Rule 9  `   Advertisement",
                "description": "Promoting your socials, servers or creations outside of #promote is strictly prohibited. DM Advertising will result in an instant ban.",
                "color": 3224376
              },
              {
                "title": "`  Rule 10  `   Use Common Sense",
                "description": "You may be warned for certain rules that are not listed here. We can't list everything but be a decent human being and don't be stupid and you'll stay. Loopholing these rules can result in severe punishment.",
                "color": 3224376
              }
            ],
            "avatar_url": "https://i.imgur.com/x56K4Lo.jpeg",
            "attachments": []
          },
          "reference": ""
        }
      ],
      "targets": [
        {
          "url": "https://discord.com/api/webhooks/1007933948824920194/3YnZucb4RH0JFMQ8z2CxpK14_TSci-3eeiC3hds4kUmyAcosufO28Z1yaBHUyhz-2xIi"
        }
      ]
    }
  ]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Template 2&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "version": 7,
  "backups": [
    {
      "name": "Template 2",
      "messages": [
        {
          "data": {
            "content": null,
            "embeds": [
              {
                "description": "**Please read the rules carefully, there are not many but we want them to be respected.**\n`(1)` **Treat everyone with respect**. Absolutely no harassment, sexism, racism, hate speech, foul language, or name-calling will be tolerated.\n`(2)` **Do not send NSFW or obscene content**. This includes text, images or links featuring nudity, sex, hard violence, or other graphically disturbing content.\n`(3)` **Do not spam or self-promote on this server** (server invites, advertisements, referral links, etc.) without permission from a Staff Member.\n`(4)` **Don’t post the same message in more than one room**. Keep discussions in the appropriate channels.\n(5) **Swearing is generally accepted**, but not if it is directed at a person, or has religious or racist overtones.",
                "color": 9043968
              }
            ],
            "avatar_url": "https://i.imgur.com/hMIEFnW.jpg",
            "attachments": []
          },
          "reference": ""
        }
      ],
      "targets": [
        {
          "url": "https://discord.com/api/webhooks/1027172261347725342/GDn87SQAXNFWJWTfaV2ZBYMmOG7yU4qEXcwVD210NkXo-HMBXVzeBn0w2wD8aGsrFcCG"
        }
      ]
    }
  ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmstrc0xh4uvvlheiren0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmstrc0xh4uvvlheiren0.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Creating and using Discord Webhooks and Embeds can greatly enhance the user experience on your Discord server and make your messages stand out. With the help of tools like discohook.org, it's easy to create and send custom Embed Messages to your server. By following the steps outlined in this tutorial, you can create a unique and beautiful Discord server that stands out from the crowd. So why not give it a try and see the difference it makes for yourself!&lt;/p&gt;

</description>
      <category>discord</category>
    </item>
    <item>
      <title>How to read a file line by line into a list in Python</title>
      <dc:creator>AnkurRanpariya2005</dc:creator>
      <pubDate>Tue, 23 May 2023 12:40:56 +0000</pubDate>
      <link>https://forem.com/ankurranpariya2005/how-to-read-a-file-line-by-line-into-a-list-in-python-g7d</link>
      <guid>https://forem.com/ankurranpariya2005/how-to-read-a-file-line-by-line-into-a-list-in-python-g7d</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Most of the time we process data from a file so that we can manipulate it from memory. This data can be numeric, string or a combination of both. In this article, I will discuss how to open a file for reading with the built-in function open() and the use of Pandas library to manipulate data in the file. This also includes reading the contents of a file line by line and saving the same to a list.&lt;/p&gt;

&lt;h2&gt;
  
  
  Things to learn on this article
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Open the file for reading&lt;/li&gt;
&lt;li&gt;Read the contents of a file line by line&lt;/li&gt;
&lt;li&gt;Store the read lines into a list data type&lt;/li&gt;
&lt;li&gt;for loop&lt;/li&gt;
&lt;li&gt;list comprehension&lt;/li&gt;
&lt;li&gt;readlines&lt;/li&gt;
&lt;li&gt;readline&lt;/li&gt;
&lt;li&gt;Read file using pandas&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  1. Open the file for reading
&lt;/h2&gt;

&lt;p&gt;Python's built-in function open() can be used to open a file for reading and writing. It is defined below based from the python documentation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;open(file, mode='r', buffering=-1, encoding=None,
     errors=None, newline=None, closefd=True, opener=None)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These are the supported values for the mode.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--v5lZhkvW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nya1w6nu5qlgvicunx2b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--v5lZhkvW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nya1w6nu5qlgvicunx2b.png" alt="Image description" width="719" height="280"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here is an example script called main.py that will open the file countries.txt for reading.&lt;/p&gt;

&lt;p&gt;main.py&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;with open('countries.txt', mode='r') as f:
    # other stuff
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative method of opening a file&lt;/strong&gt;&lt;br&gt;
An alternative way of opening a file for reading is the following.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;f = open('countries.txt', mode='r')
# other stuff
f.close()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You have to close the file object explicitly with close(). Anyhow use the with statement whenever possible as the context manager will handle the entry and exit execution of the code, hence closing the file object with close() is not needed.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Read the contents of a file line by line
&lt;/h2&gt;

&lt;p&gt;Let us go back to our code in main.py. I will add a block of code that will read the contents of file line by line and print it.&lt;/p&gt;

&lt;p&gt;main.py&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;with open('countries.txt', mode='r') as f:
    for lines in f:
        line = lines.rstrip()  # rstrip() will remove the newline character
        print(line)  # print to console
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;countries.txt&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Australia
China
Philippines
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Ensure that the main.py and countries.txt are on the same directory. That is because of the code above. In my case they are in F:\Project\8thesource path.&lt;/p&gt;

&lt;p&gt;Execute the main.py from the command line.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;PS F:\Project\8thesource&amp;gt; python main.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Australia
China
Philippines
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There we have it. We read countries.txt line by line using the open() function and file object manipulation. The first line printed was Australia followed by China and finally Philippines. It is consistent according to the sequence of how they were written in countries.txt file.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Store the read lines into a list data type
&lt;/h2&gt;

&lt;p&gt;Python has a popular data type called list that can store other object types or a combination of object types. A list of integers could be [1, 2, 3]. A list of strings could be ['one', 'two', 'three']. A list of integer and string could be [1, 'city', 45]. A list of lists could be [[1, 2], [4, 6]]. A list of tuples could be [(1, 2), ('a', 'b')]. A list of dictionaries could be [{'fruit': 'mango'}, {'count': 100}].&lt;/p&gt;

&lt;p&gt;I will modify the main.py to store the read lines into a list.&lt;/p&gt;

&lt;h3&gt;
  
  
  a) for loop
&lt;/h3&gt;

&lt;p&gt;main.py&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data_list = []  # a list as container for read lines

with open('countries.txt', mode='r') as f:
    for lines in f:
        line = lines.rstrip()  # remove the newline character
        data_list.append(line)  # add the line in the list
print(data_list)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The countries.txt is the file name. We open it for reading with symbol r. We use the for loop to read each line and save it to a list called data_list. After saving all the lines to a list via append method, the items in the list are then printed.&lt;/p&gt;

&lt;p&gt;After executing the main.py, we got the following output.&lt;/p&gt;

&lt;p&gt;output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;['Australia', 'China', 'Philippines']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  b) list comprehension
&lt;/h3&gt;

&lt;p&gt;Another option to save the read lines into the list is by the use of list comprehension. It uses a for loop behind the scene and is more compact but not beginner-friendly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;with open('countries.txt', mode='r') as f:
    data = [item.rstrip() for item in f]
print(data)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;['Australia', 'China', 'Philippines']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  c) readlines
&lt;/h3&gt;

&lt;p&gt;Yet another option to save the read lines in a list is the method readlines().&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;with open('countries.txt', mode='r') as f:
    data = f.readlines()
print(data)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output still has the newline character \n.&lt;/p&gt;

&lt;p&gt;output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;['Australia\n', 'China\n', 'Philippines']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This newline character can be removed by reading each items on that list and strip it. The readlines method is not an ideal solution if the file is big.&lt;/p&gt;

&lt;h3&gt;
  
  
  d) readline
&lt;/h3&gt;

&lt;p&gt;Another option to save the read line is by the use of the readline method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data_list = []
with open('countries.txt', mode='r') as f:
    while True:
        line = f.readline()
        line = line.rstrip()  # remove the newline character \n
        if line == '':
            break
        data_list.append(line)

print(data_list)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;['Australia', 'China', 'Philippines']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Read file using pandas
&lt;/h2&gt;

&lt;p&gt;For people aspiring to become a data scientist, knowledge of processing files is a must. One of the tools that should be learned is the Pandas library. This can be used to manipulate data. It can read files including the popular csv or comma-separated values formatted file.&lt;/p&gt;

&lt;p&gt;Here is a sample scenario, we are given a capitals.csv file that contains the name of the country in the first column and the corresponding capital in the second column. Our job is to get a list of country and capital names.&lt;/p&gt;

&lt;p&gt;capitals.csv&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Country,Capital
Australia,Canberra
China,Beijing
Philippines,Manila
Japan,Tokyo
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For this particular job it is better to use the Pandas library. The expected outputs are the country list [Australia, China, Philippines, Japan] and the capital list [Canberra, Beijing, Manila, Tokyo].&lt;/p&gt;

&lt;p&gt;Let us create capitals.py to read the capitals.csv using Pandas.&lt;/p&gt;

&lt;p&gt;capitals.py&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"""
requirements:
    pandas

Install pandas with
    pip install pandas
"""

import pandas as pd

# Build a dataframe based from the csv file.
df = pd.read_csv('capitals.csv')
print(df)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;command line&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;PS F:\Project\8thesource&amp;gt; python capitals.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;       Country   Capital
0    Australia  Canberra
1        China   Beijing
2  Philippines    Manila
3        Japan     Tokyo
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we need to get the values in the Country and Capital columns and convert those to a list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import pandas as pd

# Build a dataframe based from the csv file.
df = pd.read_csv('capitals.csv')
print(df)

# Get the lists of country and capital names.
country_names = df['Country'].to_list()
capital_names = df['Capital'].to_list()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pandas is very smart about this. It easily gets the tasks that we are after.&lt;/p&gt;

&lt;p&gt;Now let us print those list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import pandas as pd

# Build a dataframe based from the csv file.
df = pd.read_csv('capitals.csv')
print(df)

# Get the lists of country and capital names.
country_names = df['Country'].to_list()
capital_names = df['Capital'].to_list()

# Print names
print('Country names:')
print(country_names)

print('Capital names:')
print(capital_names)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;       Country   Capital
0    Australia  Canberra
1        China   Beijing
2  Philippines    Manila
3        Japan     Tokyo
Country names:
['Australia', 'China', 'Philippines', 'Japan']
Capital names:
['Canberra', 'Beijing', 'Manila', 'Tokyo']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That is it. We got the country and capital names as lists.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Conclusion
&lt;/h2&gt;

&lt;p&gt;We use the built-in function open() to open and read the contents of a file and utilize the for loop to read it line by line then save it to a list - a python data type. There are also options such as list comprehension, readlines and readline to save data into the list. Depending on the tasks and file given, we can use the Pandas library to process a csv file.&lt;/p&gt;

&lt;p&gt;For further reading, have a look on python's built-in function open() and the very useful Pandas python library.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
