Posts

Showing posts from September, 2018

Python: I/O Operations

In this article we show how we can to input/output operations using user input and file. Python supports standard keyboard input and screen output using input and print keywords, respectively. File I/O has more option depending if you want to write, read or append a file. Python also supports text and binary mode of writing,however both modes have a very minor difference based on how cr-lf ('\r\n') is handled. The following code sample demonstrate how interactive user input and output are handled in Python. After that we look at code sample to perform File I/O. Inline comments (starting with # ) clarify the purpose of specific lines of code. # Code for demonstration of Python Dictionary class DemoScreenIOClass: def ReadFromKeyboard(self): print("---------- ReadFromKeyboard") # Read a value from keyboard self.__value = input('Enter any value:') # Validation can be added using a try-except block self.__numValue =

Python: Data Collections - Dictionary

In a previous article , we looked at the features of the list data collection in Python. In this article we look at the dictionary collection type in Python. As in other languages, the dictionary is a list of key-value pairs and just like other variables in Python we do not explicitly need to define the data type of key and value. It is easy to do bulk updates in Python dictionaries using other dictionary objects, but unlike a list the slice(:) operator is not supported. Hence some bulk updates have to be done using a loop. The following code snippets demonstrate how dictionaries are created, modified and deleted. Inline comments (starting with # ) clarify the purpose of specific lines of code. # Code for demonstration of Python Dictionary class DemoDictClass: # List Initialization def Initialize(self): # Dictionaries are defined between curly brackets '{}' self._dictStr={"One" : 1, "Two":2, "Three":3, "Four"

Python: Data Collections - Lists

Like other programming languages, Python supports collection data types like arrays and dictionaries. In these series of posts, we are only looking at the features of Python 3.x where there is no longer any array data type in this version. However, there is no need to worry as the List data type in Python 3.x has all features of an array plus more.Lists are initialized like an array but Python 3.x makes it very easy to add, update and remove elements which can be done as individual elements or as slices. When dealing with collections it is important to discuss the concept of slices. A slice refers to a group of consecutive elements of the list on which a single operation can be applied. As an example, if you have to divide elements from indexes 1 through 10 by of an array 'numbers' by 2 and transfer the results to a new array 'div', the operation can be performed by the following statement: div[0:9] = numbers[1:10]/2 In languages that don't support slices, a