How to Talk to a Computer: Input and Output
Computer programs interact with users and perform tasks based on their requests.
To do this, programs receive data from the user and the external world as input and return results as output.
In Python, the input() function is used to receive input from the user, and the print() function is used to output results.
Getting Input from the User with input
When you need to ask the user something and receive a response, use the input() function.
For example, you can ask, "What is your name?" and have the user input their name through the program.
name = input("What is your name? ") print(name)
When you run the code above, the computer will ask "What is your name?" and print the name entered by the user.
Note: The
input()function always returns the input as a string.
If you want to handle numerical operations after receiving numbers from the user, you should wrap the input value with the int() function to convert it to a number.
# Convert the input age to an integer using int user_age = input("How old are you? ") age = int(user_age) # Add 1 to the input age to calculate the age next year next_year = age + 1 # Print the age next year: input age + 1 print(next_year)
Displaying Results with print
As seen in the previous example, to make the computer output something, use the print() function.
This function is used to display results on the screen, and you can also print multiple values at once.
print("Python is", "really", "fun!")
In the code above, multiple strings are separated by commas and printed on one line, with the comma-separated values connected by a space.
Therefore, this code will print "Python is really fun!".
We will learn more about the print function in the next lesson.
Lessons in this chapter ยท Mastering the Basics
- 1. What is Programming?
- 2. What is Python and Why is it Popular?
- 3. Containers for Data, Variables
- 4. Data Types in Python
- 5. Operators for Performing Operations on Variables and Values
- 6. Fill-in-the-blank quiz
- 7. How to Talk to a Computer (Input and Output)
- 8. Various Ways to Output Values with the print Function
- 9. Escaping Special Characters
- 10. Converting Between Strings and Numbers
- 11. Reserved Words with Special Meaning, Keywords
- 12. What is Indentation and Why is it Important?
- 13. Multiple-choice quiz
- 14. Coding Quiz - Return Five Times the Given Number
Communicating with the Computer: Input and Output
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help