Read Number

What Is Console Input?

  • In Python, you can read input from the user through the console using the input() function. This is useful for interactive programs where user input is required.

Steps to Read a Number:

  • The input() function reads a string value from the console. Python does not differentiate if the input is a string or number. You can convert this string to an integer or a float using int() or float() functions.

Examples:

  1. Read an Integer:
    • Steps:
      1. Use the input() function to read a number from the user.
      2. Convert the string to an integer using int().
      3. Print the number and its type.
    • Code:

      python
      # Read an integer from user
      n = int(input('Enter a number: '))
      
      # Print integer to output
      print('You entered', n)
      
      # Print type of value in n to output
      print(n, 'is of type', type(n))
      
    • Output: 

      Enter a number: 52
      You entered 52
      52 is of type <class 'int'>
  2. Read Two Integers and Perform Arithmetic:
    • Code:

      python
      # Read integers from user
      n1 = int(input('Enter a number: '))
      n2 = int(input('Enter another number: '))
      
      sum = n1 + n2
      
      print(f'Sum of {n1} and {n2} is', sum)
      
    • Output:

      Enter a number: 52
      Enter another number: 14
      Sum of 52 and 14 is 66
  3. Read a Float:
    • Steps:
      1. Use the input() function to read a number from the user.
      2. Convert the string to a float using float().
      3. Print the number and its type.
    • Code:

      python
      # Read a float from user
      n = float(input('Enter a float number: '))
      
      # Print float to output
      print('You entered', n)
      
      # Print type of value in n to output
      print(f'{n} is of type', type(n))
      
    • Output:

      Enter a float number: 3.14
      You entered 3.14
      3.14 is of type <class 'float'>

Summary:

  • You can read numbers from the console in Python using the input() function, and convert the input to the desired numeric type (int or float). Practice these steps to understand how to handle user input in Python!