7. The input() function

input(prompt)

The function input(prompt) prints the message 'prompt' to the screen and returns a line of text typed by the user with the keyboard.

This function can be used to stop the program from running until the 'Enter' key or the 'Return' key is pressed.

Examples:

>>> nombre = input('Escribe tu nombre: '); print('Hola', nombre)
    Escribe tu nombre: Montse
    Hola Montse
>>> input('Pulsa Enter para continuar')
    Pulsa Enter para continuar
    ''
>>> num = input('Escribe un número: ')
    Escribe un número: 45
>>> num
    '45'
>>> int(num)
    45
>>> float(num)
    45.0

Notice how the number entered is a text string, so we cannot perform calculations with it. To convert the text into a number you must use one of the following functions:

int('') converts a text string to an integer (no decimals)

float('') converts a text string to a floating point number.

Exercises

  1. Write a program that asks for two numbers on the screen and then prints the sum of the two.

  2. Write a program that prompts for your name on the screen and then prints a personalized greeting with your name.

  3. Write a program that prompts for two numbers on the screen and then prints the Greatest Common Divisor of the two numbers.

    Clue:

    import math
    
    # Greatest Common Divisor
    # Máximo Común Divisor de dos números a y b
    math.gcd(a, b)
    
  4. Write a program that prompts for two numbers on the screen and then prints the Least Common Multiple of the two numbers.

    Clue:

    import math
    
    # Lowest Common Multiple
    # Mínimo Común Múltiplo de dos números a y b
    math.lcm(a, b)