Computer Science Researcher • Educator • Programming Instructor
Many programs need information from the user. Python allows this through the input() function. When your program reaches an input line, it waits for the user to type something on the keyboard. Whatever the user types is always received as text (a string), even if the user enters numbers.
When you write an input instruction, Python shows a message and waits. After the user types something and presses Enter, the value is stored in a variable.
name = input("Enter your name: ")
print("Hello", name)
Explanation: The program asks the user to type a name. Whatever the user types becomes the value of the variable name.
Sample Output:
Enter your name: Ali
Hello Ali
age = input("Enter your age: ")
print("You are", age, "years old.")
Explanation: Even if the user enters 15, it is stored as text, not a number.
Enter your age: 15
You are 15 years old.
To perform calculations, the input must be converted using int() or float(). This tells Python to treat the input as a number instead of text.
age = int(input("Enter your age: "))
print("Next year you will be", age + 1)
Enter your age: 20
Next year you will be 21
price = float(input("Enter the price: "))
print("Price with tax:", price + 2.5)
Enter the price: 10.5
Price with tax: 13.0
name = input("Enter your name: ")
marks = int(input("Enter your marks: "))
print(name, "scored", marks, "marks in the test.")
Enter your name: Sarah
Enter your marks: 88
Sarah scored 88 marks in the test.
User input makes your programs interactive. Without it, programs can only show fixed information. With user input, every result depends on what the user types, making programs more powerful.
1. What does the input() function do?
Prints a message2. What type does input() return?
int3. Which function converts input to an integer?
toInt()4. Which input method is used for decimal values?
inputFloat()5. Which of the following shows correct input use?
ask("Enter name")6. What will this produce? int("5")
"5"7. What will input("Enter number: ") return?
A number8. What does this print? name = "Ali" print("Hello", name)
Hello name9. What is wrong with this? age = input("Enter age: ") print(age + 5)
Nothing10. Which code correctly converts input to a float?
number = input(float)