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!

Making executable Scripts in Unix/Linux using Python

In unix/linux, you can make executable shell scripts using Python! You can write your python codes in any file, give it executable permission, Then simply run it by double clicking! 🙂

The trick is…

At the first line of your script, type #! followed by location of your Python interpreter

#!/usr/bin/python
print 'Start coding herer'          # Python codes goes here

Saving the file with any name, give it executable permission – open a terminal/shell and type

sudo chmod a+x your-filename-with-full-path

You’re done 🙂


The Unix env Lookup Trick

On some Unix systems, you can avoid hardcoding the path to the Python interpreter
by writing the special first-line comment like this:

 #!/usr/bin/env python
 ...script goes here...

When coded this way, the env program locates the Python interpreter according to
your system search path settings (i.e., in most Unix shells, by looking in all the direc-
tories listed in the PATH environment variable). This scheme can be more portable, as
you don’t need to hardcode a Python install path in the first line of all your scripts.

Quoted from Oreilly's Learning Python

 

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

I’m going to start a new thread – Beginning Python Programming! I’ll post step-by-step easy tutorials on Python in this blog.

Please note that I’m also a beginner, and the facts which I’m learning, will be posted here. So don’t hesitate to make corrections whenever I make mistakes. 🙂

Step 1: Download Python

Download Python 3.1 or another stable version for Linux/windows/Mac/ from this link. For Ubuntu, you can download python and IDLE (the Python GUI) from Add/Remove Programs!

IDLE is enough for serving the purpose of IDE! It will be automatically installed with the package you downloaded from python website.

Step2: Code in Python, copile & run it!

Using the IDLE

IDLE is the best IDE for a quick coding practise. In the IDLE, you can type a single line of code and see the output immediately. No need to create a source file or copile it! This is a great tool for quick demonstration of a bit of code.

You can type as many Python commands as you like; each is run immediately after it’s entered. Moreover, because the IDLE automatically prints the results of expressions you type, you don’t  need to say “print” explicitly at this prompt. No need of typing a semicolon after each line of code.

In Windows, Open the Python IDLE (you can find it in the Start menu )

In Ubuntu/Linux, you can find the IDLE in your main menu > Programming

Alternately, if you don’t have the IDLE installed, you can obtain the same effect from your Command-Prompt:

In windows, open a Command Prompt from Start Menu, Then type:

c:\python26\python.exe

Note, here I’m using Python 2.6, so the  I typed python26 in the command above. If you have a different version, your command will change! Go to your C directory, and look for a folder named Python**, herer ** reflects the version.

In Linux or Unix, open a terminal (shell) and type:

/usr/local/bin/python (or /usr/bin/python)

Writing Source Code in files and running it:

Although you can type codes in the IDLE, they get lost as soon as the IDLE quits. So, you can store your source codes at source files and then run your codes from command prompt. We generally use a .py extension for Python source-files.

For a quick demonstration, create a new file called mycode.py and open it for editing by your favourite editor (I’ll prefer the IDLE editor)

Type following lines of codes in the file just opened:

echo "Hello, World"           # This is a comment! Anything after the # is ignored
echo 2 ** 4                   # This will output 2^4

Save the file. Open your command-prompt to run. Just type the full path of the source file after the python command

Windows users:

c:\python26\python c:\codes\mycode.py

Assuming that the source file is available at C:\codes directory!