Python 3 Read from Standard Input (stdin) Like C or Java

I will be using Python3 to read from standard input (or console). I will present two ways of doing this.

First Example

Input (data.txt)

First line of input will contain an integer which tells how many of lines (of data) will follow up. In each of the following lines, there will be one integer and and one floating-point (decimal) number, separated by a space:

3
1 2.3
3 4
5 6.0

Code (iotest.py)

if __name__ == '__main__':
    # Reading the first line and converting it to an integer
    num_entries = int(input())

    # Running a for loop to read each of the following lines
    for i in range(num_entries):
        current_line = input()
        # Getting the two values separated by space in variables `a` and `b`
        a, b = current_line.split()
        a, b = int(a), float(b)
        print(a, b)

Run the program

python3 iotest.py < data.txt

Second Example

Input (data.txt)

In this example, data file exactly looks like the one from first example, except that the first line is missing. Which means, we do not know how many data to read. We would have to run a while loop to read lines till there is and EoF (End of File) which tells us there is nothing more to read.

1 2.3
3 4
5 6.0

Code (iotest2.py)

if __name__ == '__main__':
    try:
        # Running a while loop since we don't know how many lines to read.
        while True:
            current_line = input()
            # Getting the two values separated by space in variables `a` and `b`
            a, b = current_line.split()
            a, b = int(a), float(b)
            print(a, b)
    except EOFError:
        # There is nothing more to do when we reach End of File (EOF)
        pass

Run

python3 iotest2.py < data.txt

Concluding Notes

  • You can run the programs without saving input data in a file. Just type python3 iotest.py and then enter data.
  • Be sure to use Python 3 only as the code will not work in Python 2
  • We are using input() built-in method of Python 3 which reads a single line and returns it as a string. So we have to convert them to appropriate data type (int/float).

Python Tutorial: Dictionaries (Maps): Advanced features

Sorting: more loop operations of maps

Suppose, we have the following map:

>>> D = {'a': 1, 'b': 2, 'c': 3}
>>> D
{'a': 1, 'c': 3, 'b': 2}

We can create a list of keys of a map, then use a for loop to treat it as a sequence:

>>> Ks = D.keys( ) # Unordered keys list
>>> Ks
['a', 'c', 'b']
>>> Ks.sort( ) # Sorted keys list
>>> Ks
['a', 'b', 'c']
>>> for key in Ks: # Iterate though sorted keys
print key, '=>', D[key]
a => 1
b => 2
c => 3

Checking existance of a key:

Fetching a non-existant key is error. Consider the following code snippet:

>>> D
{'a': 1, 'c': 3, 'b': 2}
>>> D['e'] = 99 # Assigning new keys grows dictionaries
>>> D
{'a': 1, 'c': 3, 'b': 2, 'e': 99}
>>> D['f'] # Referencing one is an error
...error text omitted...
KeyError: 'f'


We can use following method to check whether a key exists:

>>> D.has_key('f')
False
>>> if not D.has_key('f'):
print 'missing'
missing

Python Tutorial: Dictionaries (Key-value pair Maps) Basics

Dictionary in Python is a data-structure also known as map. Chances are you’re already familiar with them, if using Associative Arrays in PHP or Hashtables in C++ or Java. You may imagine a dictionary as an array, where instead of numerical indexes (the first element of array is indexed as 0, the second element is indexed by 1 and so on), you use string indexes. Each element of a map is accessed (or, indexed) by an unique “key”; so they are also known as key-value pairs. Dictionaries are not sequences, so the order in which elements are added to the dictionary doesn’t matter.

Example

Suppose, we want a data-structure to store information about a cooking recipe. For the recipe, we want to store which food (dish) we’re cooking, how many quantities it serve, and the color of the food being  prepared (don’t ask me why).

You can create a map using this syntax: variable_name = {key:value}

In the following examples, any text after “>>>” is actual code that you use in your Python scripts. You can also type this code in Python command line interpreter. Any line not beginning with “>>>” indicates an output of the previous code.

Code:
>>> D = {'food': 'pudding', 'quantity': 4, 'color': 'pink'}

>>> D['food'] # Fetch value of key 'food'
'pudding'

>>> D['quantity'] += 1 # Add 1 to 'quantity' value

>>> D
{'food': 'pudding', 'color': 'pink', 'quantity': 5}

Alternately, you can create an empty map, and insert key-value pairs later. Unlike Lists (arrays in Python), you can perform out-of-bound assignments:

Code:
>>> D = {}

>>> D['name'] = 'Bob' # Insert element on-the-fly

>>> D['job'] = 'dev'

>>> D['age'] = 4

>>> D
{'age': 4, 'job': 'dev', 'name': 'Bob'}

>>> print D['name']
Bob

Nesting

Like lists, nesting is also possible in maps. Consider the following code pattern:

Code:
>>> rec = {'name': {'first': 'Bob', 'last': 'Smith'},
                  'job': ['dev', 'mgr'],
                  'age': 40.5}

>>> rec['name'] # 'Name' is a nested dictionary
{'last': 'Smith', 'first': 'Bob'}

>>> rec['name']['last'] # Index the nested dictionary
'Smith'

>>> rec['job'] # 'Job' is a nested list
['dev', 'mgr']

>>> rec['job'][-1] # Index the nested list
'mgr'

>>> rec['job'].append('janitor') # Expand Bob's job description in-place

>>> rec
{'age': 40.5, 'job': ['dev', 'mgr', 'janitor'], 'name': {'last': 'Smith', 'first':
'Bob'}}

Python Basics: Indent

Previous Article: Beginning Python Prgramming! How to Download, install, compile & run program in Python

In this post I’ll point out some details about the Python language. Important concepts to be clarified.

Python maintains indention strictly:

In python, you should maintain indention strictly! This is necessary to tell python which portion of code is under a block. For example, consider the loop segment below:

 

As you can see, there is no Curly-braces to identify where a loop starts and where ends! Thus, you must maintain indention strictly.

 

 

This entry will be updated eventually!