Saturday 11 February 2017

Accepting user input in Python



The ability to accept user input is a must in any programming language and the python interpreter is no different such that it provides us with a neat and easy ways to accept and process user input.

In this article I'll demonstrate the use of two functions one to gather string input and the other to gather integer input.

input():
We use the input function to gather integer input from the user. To use it we simply type the input function with the text to be displayed on the screen. For example: input("display this on screen").
Generally we'd assign the value obtained from the input function to a variable for future use.


raw_input():
We use the raw_input function to gather string input from the user. It's usage is exactly same as that of the input function. For example, we type raw_input("text to be displayed"). The string "text to be displayed" is output to the terminal. The user will feed some input which will be stored in a variable for future use.

Given below is a simple sample script:

root@buntu:~/py_scripts# cat in.py
#!/usr/bin/python

###get input from user

name = raw_input("What is your name?? ")


age = input("what is your age? ")


print "so", name,
print "your name is", name, "and age is", age, "years"


The script will prompt the user for name and age. It will store the input provided by the user in variables name and age and will then print the result.
When we print variable names along with other strings in a print statement we'll exclude the variables from the double quotes and use commas as separaters.

Here is a sample execution:

root@buntu:~/py_scripts# ./in.py
What is your name?? sahil
what is your age? 27
so sahil your name is sahil and age is 27 years

3 comments:

  1. Hi Sahil, Wonderful blod. I have a request Would u please be able to post a python script to monitor for a process based off its name & fire an email alert if the process stops ? Like wise, would you please be able to post some examples of using psutil to send an alert when CPU or Temp loads crosses xyz threshold ?

    Thanks in advance.

    ReplyDelete
    Replies
    1. Hi Nick, I'm glad that you found the articles in the blog useful. About the monitoring scripts in Python, I'll surely work on it and should have a post out in the next few days.

      Delete
  2. Typo. Correction - blog* in my earlier post.

    ReplyDelete

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...