Getting input from Keyboard In Python

To get input from Keyboard In Python use the built-in function input(prompt) which displays the prompt value and accepts the input on the same line

Console Input Updated 22 Sep 2016 1 min read

Reading values entered from keyboard and using them to calculate certain results is an essential programming exercise.
In python, to receive input from standard input the function input() is used.

The built-in method input() accepts an optional "prompt" parameter.
When provided with the "prompt" parameter it prints the prompt and waits for the input
on the same line.

Example1: Getting a value from keyboard and treating the value as string

python
>>> MyFavoriteCity = input("Enter your favorite city")

            Enter your favorite cityNew York

            >>> print(MyFavoriteCity)

            New York

The input() method returns the input entered in string format. Very often we may need to get input as an integer or a floating point number.
In such cases the string value returned from the input() function needs to be manually formatted before used in any arithmetic operations.

Example2: Getting multiple values from keyboard and treating the values as integers

python
'''Implementation of Euclid's algorithm to find the

   Greatest Common Divisor of two positive integers'''

def findGreatestCommonDivisor(aNumber1, aNumber2):

    remainder       = 0

    if(aNumber1 <= 0 or aNumber2 <= 0 ):

        print("One or both numbers have got a zero or negative value")

        return -1;

    while True:

        remainder = aNumber1 % aNumber2

        if(remainder == 0):

            break;

        aNumber1 = aNumber2

        aNumber2 = remainder

    return aNumber2;

# Get 2 numbers from standard input

Number1 = input("Enter Number1:")

Number2 = input("Enter Number2:")

#Convert the keyboard input strings to integers

Number1 = int(Number1)

Number2 = int(Number2)

#Find Greatest Common Divisor of two positive integers using Euclid's algorithm

GCD = findGreatestCommonDivisor(Number1, Number2)

#Print the GCD value found by the algorithm

print('Greatest Common Divisor of {} and {} is {}'.format(Number1, Number2, GCD))

Output of the GCD Program

Output
Python-Computer:PythonExamples pythonUser$ python GCD.py

Enter Number1:63

Enter Number2:49

Greatest Common Divisor of 49 and 63 is 7