How to Make Your Python Program Interactive with input()
Python Interactive Input Method
python input methodDEVOLOGISTIntroduction
So far, your programs have been one-way streets. You write code, and it runs. But what if you want your program to ask the user a question and wait for an answer? You use the input() function.
Basic User Input
The input() function pauses your program and waits for the user to type something and press Enter.
name = input("What is your name? ")print("Hello, " + name + "! Nice to meet you.")
The "Gotcha": Data Types
Here is the most important thing to remember: Python treats everything from input() as a string (text).
Even if the user types a number, Python sees it as text. If you try to do math with it, you will get an error.
age = input("How old are you? ")# If user types 25, this code will fail:print(age + 1)
Result: TypeError: can only concatenate str (not "int") to str.
The Solution: Casting
To fix this, you must convert the input to the type you need (like int) using casting.
age = input("How old are you? ")age = int(age) # Convert the string to an integerprint(age + 1) # Now this works!
Mini-Project: The Greeter
Combine what you've learned. Ask the user for their name and their birth year, then calculate their current age.
name = input("What is your name? ")year = input("What year were you born? ")age = 2026 - int(year)print(f"Hi {name}, you are {age} years old!")
Conclusion
The input() function is your bridge to interactive programming. By understanding casting, you can successfully take numbers, dates, and other data types from the user.
