Bottom Page

• 0 Vote(s) - 0 Average
• 1
• 2
• 3
• 4
• 5
 The difference between two functions Motley_Cow Programmer named Tim Posts: 7 Threads: 3 Joined: Sep 2019 Reputation: 0 Likes received: 0 #1 Dec-03-2019, 12:11 AM I am a newbie to python and going through the NLTK book to learn a bit about using python for natural language processing. This post is not about NLTK, but about the difference in object classes that occur in the following two functions: The first function is used to find the percentage of times that a single word occurs within the body of a text: ```def percent1(text, word): a = text.count(word) #counts the number of 'words' (items) in the list (i.e. text) b = len(text) perc = a / b print(f"{perc} %") #an example of the output of this function is: 7.2385e-05%```The second function does the same thing, except it returns the output as a decimal: ```def percent2(text, word): from decimal import Decimal a = text.count(word) b = len(text) perc = Decimal(a / b) output = round(perc, 8) #rounds the variable perc to the 8th decimal place print(f"{output} %") #an example of the output of this function #(from the same text) is: 0.00007285%```In trying to understand the difference between floats and integers, my question is this: Does the first function return a float (floating point integer?) while the second function returns a decimal integer? Would stating it that way be correct? (My apologies, I'm brushing up on math while coding, but I am not the most adept with such terminology) All thoughts and considerations are appreciated. Larz60+ aetate et sapientia Posts: 9,188 Threads: 331 Joined: Sep 2016 Reputation: 398 Likes received: 1202 #2 Dec-03-2019, 12:52 AM division of two integers returns a float ```>>> a = 6 >>> b = 3 >>> c = a/b >>> print(f"type(a): {type(a)}, type(b): {type(b)}, type(c): {type(c)}") type(a): , type(b): , type(c): >>> ``` midarq Programmer named Tim Posts: 11 Threads: 4 Joined: Sep 2019 Reputation: 1 Likes received: 2 #3 Dec-03-2019, 12:57 AM Yes. You can always use the type function to test that. Examples (Out is the output for the line of code above it): ```from decimal import Decimal 2/5 Out: 0.4 type(2/5) Out: float Decimal(2/5) Out: Decimal('0.40000000000000002220446049250313080847263336181640625') type(Decimal(2/5)) Out: decimal.Decimal 2//5 Out: 0 type(2//5) Out: int ``` « Next Oldest | Next Newest »

Top Page

Forum Jump:

Users browsing this thread: 1 Guest(s)