Thursday, October 29, 2020

Python Keyword & Statistics Library

 Keyword Library: 

Keyword is a module used to determine whether the string is a keyword or not using the function iskeyword. It also has one attribute kwlist which returns the list of keywords defined by the interpreter. Below program illustrates the use of Keyword module in Python 


import keyword #Module related to Keywords 
Word ="elseif" 
print(keyword.iskeyword(Word)) #False - Check whether string is Keyword or not 
print(keyword.kwlist) #Returns the list of Keywords definded by interpreter 


Statistics Library Functions: 

Statistics is a python library containing functions used to perform mathematical statistics. This is not a third-party library and comes with Python installation.  


This library functions only on Integer, Float, Decimal & Fraction data provided as Lists, Tuples, Sets, Dictionaries (Values can be Integer/Float/Decimal/Fraction). If the data does not meet the constraints of the function, StatisticsError is thrown. Below are the functions present in Statistics library 


  • mean - Takes data as an argument and returns arithmetic mean. Needs a non-empty dataset. 
  • fmean - Takes data as an argument and returns arithmetic mean in terms of floating point and is faster than mean method 
  • geometric_mean - Takes non empty data set containing only positive numbers and return geometric mean of the data as floating-point number 
  • harmonic_mean - Takes non empty data set not containing negative numbers and returns harmonic mean of the data as floating-point number 
  • median - Takes non empty data set and returns median of the data 
  • mode - Takes not only numbers, but strings also and returns mode of the data. If there is more than one mode, first occurred mode will be returned if python version is greater than or equal to 3.8. Else, StatisticsError is thrown 
  • multimode - Takes not only numbers, but strings also and returns all possible modes of the data as a list 
  • variance - Takes non empty data set and returns variance of the given data 
  • stddev - Takes non empty data set and returns standard deviation of the data 

Below is the demo program showing the use of above functions in statistics library 


import statistics 
print(statistics.fmean([1,2,3,4,5])) #3 
print(statistics.fmean((1,2,3,4,5))) #3.0 
print(statistics.geometric_mean((1,2,3,4,5))) #2.6 Approximately 
print(statistics.harmonic_mean({1,2})) #1.3 Approximately 
print(statistics.median([1,7,-1,4,5.0])) #4 
print(statistics.mode(["a",1,'n',"c","a"])) #a 
print(statistics.mode(["a",1,'n',"c","a",1])) #a In Python Version < 3.8 it throws StatisticsError 
print(statistics.multimode(["a",1,'n',"c","a",1])) #['a',1] 
print(statistics.multimode("Manideep")) #['e'] 
print(statistics.variance([1,2,3,4,5]))#2.5 
print(statistics.stdev([1,2,3,4,5]))#1.58 Approximately