Getting input from Keyboard In Python

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

>>> 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

'''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:

Python-Computer:PythonExamples pythonUser$ python GCD.py

Enter Number1:63

Enter Number2:49

Greatest Common Divisor of 49 and 63 is 7


Copyright 2024 © pythontic.com