Saturday, August 27, 2016

Running Python script on Unix



So far we have learned about basics of Python including how to print anything in Python and its major data types. We have also seen different types of loop and function declarations. In this article, we will write small function and save it to a file (.py) and then we will execute it from terminal

Writing first Python script  

We will write a function, which will accept user input and validate, if user has entered incorrect input. It will keep on prompting for user input until it gets correct input.


def getFloatFromUser(prompt):
    while True:
        number = raw_input(prompt)
        try:
            number = float(number)
        except:
            print 'That is not a float, please try again.'
            continue
        # everything OK
        return number

myFloat = getFloatFromUser('Please enter a float: ')
print myFloat


We have saved above code to my_first_python_script.py file.


Running Python script  

We have saved our python file to our tutorial folder. Now, we will open the terminal and run this file, but before that, we need to change file to executable.
 $chmod +x /Desktop/MyTutorial/Python/my_first_python_script.py
Once, you have changed file to executable , you need to type following command to execute your python script :
 $python /Desktop/MyTutorial/Python/my_first_python_script.py

The script will start executing and expects valid input, please refer below snippet : 


$ python /Desktop/MyTutorial/Python/my_first_python_script.py
Please enter a float: tt
That is not a float, please try again.
Please enter a float: las
That is not a float, please try again.
Please enter a float: sdf
That is not a float, please try again.
Please enter a float: 90
90.0

Until user enters valid input, it will keep on prompting for valid input. Once, user enters valid input, it will display it to screen and come out from the loop. 

That's it !!

No comments:

Post a Comment