In this post, we will understand the concept of input function in Python. The input()
function is used to take user input from the standard input such as the keyboard. It prompts the user with a message (optional), waits for the user to enter some text, and then returns the text entered by the user as a string.
Here’s the basic syntax of the input()
function:
user_input = input("Prompt message: ")
- The optional string parameter
Prompt message:
is the message displayed to the user, prompting them to enter some text. This parameter is optional.- The function returns a string containing the text entered by the user.
Here’s a simple example:
user_name = input("What is your name?") print(f"Hello {user_name}. How are you doing today?") # Output: # What is your name?Prakash # Hello Prakash. How are you doing today?
When you run the above code, it will display “What is your name? ” on the screen, and wait for the user to enter their name. After the user enters their name and presses enter key, the program will output Hello {user_name}. How are you doing today? where the usern_name will be replaced by the input provided by the user.
Here are a few more examples of using the input()
function in Python.
Example 1 – Calculator program using input function
n1 = int(input("Enter first number: ")) n2 = int(input("Enter second number: ")) operation = input("Enter operation (+, -, *, /)") if operation == "+": print(n1 + n2) elif operation == "-": print(n1 - n2) elif operation == "*": print(n1 * n2) elif operation == "/": if n2 != 0: print(n1 / n2) else: print("Error: Division by zero!") else: print("Invalid operation") # Output # Enter first number: 100 # Enter second number: 100 # Enter operation (+, -, *, /)+ # 200
Example 2 – Temperature Conversion Program
# Temperature conversion program temp_celsius= float(input("Enter temperature in Celsius: ")) temp_fahrenheit = (temp_celsius * 9/5) + 32 print("Temperature in Fahrenheit:", temp_fahrenheit) # Output: # Enter temperature in Celsius: 100 # Temperature in Fahrenheit: 212.0