Input Operations

What Is the input() Function?

  • The input() function in Python allows you to get input from the user. This is useful for interactive programs where the user provides information while the program is running.

How to Use It:

  • The basic way to use the input() function is:

    python
    variable_name = input("Your prompt message here")
    
    • prompt is a message that tells the user what to input.
    • The input() function returns the user’s input as a string.

Examples and Exercises:

  1. Reading a String Value from the User:
    • Let's read a string input from the user and print it:

      python
      x = input('Enter a value: ')
      print('You entered:', x)
      
    • When the user types hello and presses Enter:

       
      Enter a value: hello
      You entered: hello
      
  2. Reading a Number Using input():
    • By default, the input() function returns a string. You can convert this string to a number using int(), float(), or complex().

      python
      x = int(input('Enter an integer: '))
      print('You entered:', x)
      x = float(input('Enter a float: '))
      print('You entered:', x)
      
    • When the user types 26 and 69.54:

       
      Enter an integer: 26
      You entered: 26
      Enter a float: 69.54
      You entered: 69.54
      
  3. Using input() Without a Prompt:
    • You can also use input() without providing a prompt message:

      python
      x = input()
      print('You entered:', x)
      
    • When the user types nature:

       
      nature
      You entered: nature
      

Summary:

  • The input() function is a powerful tool for getting user input in your programs. It reads input as a string, but you can convert it to other data types as needed. Practice using input() to make your programs interactive and user-friendly!