The input() function in Python is used to take user input from the console.
Here’s an example of how to use the input() function:
Python
name = input("Enter your name: ")
print(name)
Output
Enter your name: EasyExamNotes
EasyExamNotes
In this example:
- The input(“Enter your name: “) prompts the user to enter their name.
- When the user types something and presses Enter, input() returns the user’s input as a string.
- The entered name is then stored in the variable name.
- Finally, the program print the entered name.
Question: Why is it important to convert the result of input()
to a numeric type using int()
or float()
if numerical operations are intended?
Answer: input()
always returns a string. To perform numerical operations, such as addition or multiplication, the input must be converted to a numeric type like int or float using int()
or float()
. This enables mathematical calculations to be executed effectively.
Python
age = int(input("Enter your age: "))