Getting User Input in Python
When creating a program, there are times when you need to gather information from the user. In such cases, the input() function comes into play.
The input function returns data entered by the user through the keyboard as a string (text data).
How is it used?
The input() function displays a message to the user and waits for the user's input.
Once the user presses the enter key, the input process ends, and the entered content is returned as a string.
user_input = input("Please enter your name:") # Displays a message to the user and waits for the user's input print("Welcome", user_input) # Outputs "Welcome [user input]"
When is it typically used?
The input() function is used when you need to gather settings, information, or data from the user that is required for the program to operate.
name = input("Please enter your name: ") hobby = input("Please enter your hobby: ") print(name + "'s hobby is " + hobby + ".")
Precautions
The input function always returns the data received from the user as a string (text data).
If you need a number instead of text, wrap the input() function with int() to convert the response.
user_input = input("Please enter a number: ") number = int(user_input) print(number)
Coding Practice
Try using Python's input() function to ask the user a question and respond based on their answer.
Click the green Run button to see how the input works in action.
Lessons in this chapter Β· Master the Fundamentals of Python
- 1. What is Programming and What Benefits Can You Gain from Learning It?
- 2. Coding and Viewing Your Results in Real-Time
- 3. Are There Levels in Programming Languages?
- 4. Features of Python and Simple Code Example
- 5. Reasons Why Python is Popular
- 6. Why is Indentation Important in Python?
- 7. Printing Output in Python
- 8. Getting User Input in Python
- 9. Multiple-choice quiz
- 10. Statements and Expressions
- 11. Predefined Reserved Words in Python - Keywords
- 12. How to Name Variables and Functions Sensibly
- 13. Explaining Code with Comments
- 14. What are Identifiers?
- 15. A Container for Data, Variables
- 16. Important Points When Assigning Values to Variables
- 17. Symbols for Performing Operations, Operators
- 18. Literals Representing Data
- 19. Coding Quiz - Return 10 Times the Given Number
- 20. Multiple-choice quiz
- 21. Fill-in-the-blank quiz
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help