-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPython User Input 1
More file actions
298 lines (199 loc) · 17.5 KB
/
Copy pathPython User Input 1
File metadata and controls
298 lines (199 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
Reading Input From the Keyboard
Writing Output to the Console
Combining Python Input and Output in a Practical Example
Reading Input With Advanced Features
Printing Output With Advanced Features
Conclusion
For a program to be useful, it often needs to communicate with the outside world. In Python, the input() function allows you to capture user input from the keyboard, while you can use the print() function to display output to the console.
These built-in functions allow for basic user interaction in Python scripts, enabling you to gather data and provide feedback. If you want to go beyond the basics, then you can even use them to develop applications that are not only functional but also user-friendly and responsive.
By the end of this tutorial, you’ll know how to:
Take user input from the keyboard with input()
Display output to the console with print()
Use readline to improve the user experience when collecting input on UNIX-like systems
Format output using the sep and end keyword arguments of print()
To get the most out of this tutorial, you should have a basic understanding of Python syntax and familiarity with using the Python interpreter and running Python scripts.
Get Your Code: Click here to download the free sample code that you’ll use to learn about basic input and output in Python.
Take the Quiz: Test your knowledge with our interactive “Basic Input and Output in Python” quiz. You’ll receive a score upon completion to help you track your learning progress:
Basic Input, Output, and String Formatting in Python
Interactive Quiz
Basic Input and Output in Python
In this quiz, you'll test your understanding of Python's built-in functions for user interaction, namely input() and print(). These functions allow you to capture user input from the keyboard and display output to the console, respectively.
Reading Input From the Keyboard
Programs often need to obtain data from users, typically through keyboard input. In Python, one way to collect user input from the keyboard is by calling the input() function:
The input() function pauses program execution to allow you to type in a line of input from the keyboard. Once you press the Enter key, all characters typed are read and returned as a string, excluding the newline character generated by pressing Enter.
If you add text in between the parentheses, effectively passing a value to the optional prompt argument, then input() displays the text you entered as a prompt:
>>> name = input("Please enter your name: ")
Please enter your name: John Doe
>>> name
'John Doe'
Adding a meaningful prompt will assist your user in understanding what they’re supposed to input, which makes for a better user experience.
The input() function always reads the user’s input as a string. Even if you type characters that resemble numbers, Python will still treat them as a string:
>>> number = input("Enter a number: ")
Enter a number: 50
>>> type(number)
<class 'str'>
>>> number + 100
Traceback (most recent call last):
File "<python-input-1>", line 1, in <module>
number + 100
~~~~~~~^~~~~
TypeError: can only concatenate str (not "int") to str
In the example above, you wanted to add 100 to the number entered by the user. However, the expression number + 100 on line 7 doesn’t work because number is a string ("50") and 100 is an integer. In Python, you can’t combine a string and an integer using the plus (+) operator.
You wanted to perform a mathematical operation using two integers, but because input() always returns a string, you need a way to read user input as a numeric type. So, you’ll need to convert the string to the appropriate type:
>>> number = int(input("Enter a number: "))
Enter a number: 50
>>> type(number)
<class 'int'>
>>> number + 100
150
In this updated code snippet, you use int() to convert the user input to an integer right after collecting it. Then, you assign the converted value to the name number. That way, the calculation number + 100 has two integers to add. The calculation succeeds and Python returns the correct sum.
Note: When you convert user input to a numeric type using functions like int() in a real-world scenario, it’s crucial to handle potential exceptions to prevent your program from crashing due to invalid input.
The input() function lets you collect information from your users. But once your program has calculated a result, how do you display it back to them? Up to this point, you’ve seen results displayed automatically as output in the interactive Python interpreter session.
However, if you ran the same code from a file instead, then Python would still calculate the values, but you wouldn’t see the results. To display output in the console, you can use Python’s print() function, which lets you show text and data to your users.
Remove ads
Writing Output to the Console
In addition to obtaining data from the user, a program will often need to present data back to the user. In Python, you can display data to the console with the print() function.
To display objects to the console, you pass them as a comma-separated list of arguments to print(). By default, the output that print() produces separates objects by a single space and appends a newline to the end of the output:
>>> first_name = "John"
>>> last_name = "Doe"
>>> print("Name:", first_name, last_name)
Name: John Doe
You can specify any type of object as an argument to print(). If an object isn’t a string, then print() converts it to an appropriate string representation before displaying it:
>>> numbers = [1, 2, 3]
>>> print(numbers)
[1, 2, 3]
>>> age = 42
>>> print(age)
42
>>> name = {"first": "John", "last": "Doe"}
>>> print(name)
{'first': 'John', 'last': 'Doe'}
>>> print(len)
<built-in function len>
As you can see, you can display complex types like lists, dictionaries, and even functions to the console with print().
Combining Python Input and Output in a Practical Example
Now that you know how to read input from users with input() and display output with print(), you can combine these tools to create a small two-line program that greets a user by their name.
The program will start by prompting the user to enter their name and capture that input using input(). Then, you can use print() to output a personalized greeting that includes the entered name:
greeter.py
name = input("Please enter your name: ")
print("Hello", name, "and welcome!")
The script introduces a small interaction with your user. When the program runs, it temporarily pauses, awaiting input from the user. Once the user provides their name and presses the Enter key, the program immediately responds with a warm greeting:
Note that print() automatically adds spaces between arguments when concatenating multiple arguments into a single string.
The small program in greeter.py collects user input and responds with console output in only two lines of code:
Line 1 prompts the user with a helpful message. The input() function then collects the user’s response as a string, which you assign to the name variable.
Line 2 assembles a custom greeting using hardcoded strings and the value stored in name. The print() function combines the greeting with the user’s input and displays it to the console.
This example brings together the input() and print() functions to accomplish a specific purpose, using the strengths of each function:
input() gathers user data, making the program interactive and adaptable to different users.
print() displays feedback based on that data, which allows the program to communicate its response to the user in a friendly, personalized way.
In a real-world application, these basic tools can support more complex workflows. For example, after welcoming a user, your program might offer further options or prompt them for more specific input to guide them through a process.
Expand the collapsible section below to continue practicing with a slightly more complex example:
If you’ve successfully built the guess-the-number game and you want another challenge, then you can expand the collapsible section below for a second task:
Collecting user input and displaying data back to the user comes in handy in many scenarios. Can you think of another practical use case? If you do, share your thoughts in the comments section below.
Remove ads
Reading Input With Advanced Features
In the previous sections, you explored how the input() function allows your program to pause and wait for the user to provide information. However, depending on the operating system and shell that you’re working with, the standard input() may have some limitations that can affect user experience.
Note: If you’re on Windows 10 or newer, then you can skip this section. Windows 10 shipped with console improvements that allow for improved keyboard editing and selection. This works natively on Command Prompt and PowerShell.
In some configurations, specifically on UNIX-like systems and Windows versions before Windows 10, you’ll notice that you can’t use arrow keys for navigating through typed characters or to recall previously entered commands:
This can become cumbersome in interactive programs where users might want to correct mistakes or quickly repeat commands.
There’s a straightforward way to improve input functionality just by importing an additional module. The module that you can use depends on whether you’re on a UNIX-like system or on Windows, so make sure to select your operating system from the options below:
Windows
Linux + macOS
If you’re on a Windows version above Windows 10, then you don’t need to do anything. Advanced input editing capabilities and history recall are natively supported in Command Prompt and PowerShell since Windows 10. You can try running the code that you’ll see further down without importing the readline module, and you should still have access to all of the mentioned features.
However, if you’re working on a Windows version before Windows 10, then you need to install a third-party library to get access to this functionality. One such library is pyreadline3, which you can install with Python’s package manager, pip:
PS> py -m pip install pyreadline3
After the installation is done, the pyreadline3 library will provide similar functionality to the GNU Readline library available on UNIX-like systems. While it mimics the behavior of the readline module from Python’s standard library, pyreadline3 is not a direct substitute as it may have differences due to underlying system variations.
The readline.py file of the third-party project ensures that when you import readline in your Python code, your code will instead use the pyreadline3 implementation.
To activate the improved input functionality in your input interface, you only need to import readline:
improved_input.py
import readline
while (user_input := input("> ")).lower() != "exit":
print("You entered:", user_input)
Try running the code snippet above, which drops you into an infinite loop that allows you to test input editing and history recall:
Use the Left and Right arrow keys to navigate within the input line.
Use Ctrl+A and Ctrl+E to move to the beginning and end of the input line, respectively.
Recall previous inputs using the Up and Down arrow keys.
You can exit the loop that you set up in improved_input.py and end the example program by typing exit.
Integrating enhanced input features can significantly improve the user experience, especially in interactive applications like command-line tools or games:
This enhancement is particularly valuable in scenarios where users are expected to input commands frequently or make complex entries with frequent edits.
It’s important to note that the features provided by readline and pyreadline3 are natively supported only in console environments and may not work in all Integrated Development Environments (IDEs). IDEs often handle input differently from standard terminal environments. Additionally, some key bindings and functionalities may vary depending on the system configuration and the specific implementation of the module.
By extending the capabilities of input(), your programs can offer a more robust and user-friendly interface, accommodating smoother data entry and manipulation processes.
In the next section, you’ll continue to explore how you can refine output appearance and formatting using some advanced features of print().
Remove ads
Printing Output With Advanced Features
The print() function takes additional arguments that provide some control over the format of the output. Each of these is a special type of argument called a keyword argument.
Keyword arguments have the form <keyword>=<value>. You need to pass them at the end, after the list of objects that you want to display.
Note: You can only achieve basic formatting of console output with print(). If you need more precise control over the appearance of your data, then you can use Python’s f-strings to format the object before passing it to print().
In this section, you’ll see how the following keyword arguments affect the console output that print() produces:
sep: This argument allows you to specify how to separate multiple objects when they are printed.
end: Use this argument to set what Python prints at the end of a print() call.
file: This allows you to redirect the output to any file-like object.
flush: Use this argument to flush the output stream, effectively bypassing any buffering.
Adding the keyword argument sep=<str> causes Python to separate objects by <str> instead of by the default single space:
>>> print("input", "output")
input output
>>> print("input", "output", sep="/")
input/output
>>> print("input", "output", sep="...")
input...output
>>> person = {"first_name": "John", "last_name": "Doe"}
>>> for key, value in person.items():
... print(key, value, sep=" -> ")
...
first_name -> John
last_name -> Doe
In these examples, you’ve used different strings, such as "/", "...", and " -> " to separate the objects that you’re asking print() to display. You can use the sep keyword to specify any arbitrary string as the separator:
>>> print("input", "output", sep="Real Python")
inputReal Pythonoutput
However, passing a string such as "Real Python" as the separator will rarely make a lot of sense. In practice, you’ll probably want to stick with passing a well-readable separator symbol like in the previous examples.
To squish objects together without any space between them, you specify an empty string ("") as the separator:
>>> print("input", "output", sep="")
inputoutput
Finally, you can add a linebreak in between each item by passing the newline character (\n) to sep:
>>> print("input", "output", sep="\n")
input
output
Separating objects with a newline character displays each of them on an individual line, which can be helpful when you need to inspect more complex objects. Sometimes, you may even want to separate them with two consecutive newline characters (\n\n) to group your output better and make it more readable.
The keyword argument end=<str> causes Python to terminate the output by <str> instead of by the default newline:
>>> first = "John"
>>> last = "Doe"
>>> print(first, last, end="!")
John Doe!>>>
In this example, you’ve replaced the default newline end character with an exclamation mark. Notice how this breaks the usual neat way that calling print() drops you into a new empty line. Now you get to see an exclamation mark followed directly by Python’s input prompt (>>>) because you told print() not to write a newline character.
You can also pass an empty string to this parameter to side-step the default newline functionality. For example, assume that you’re displaying values in a loop:
>>> for number in range(10):
... print(number)
...
0
1
2
3
4
5
6
7
8
9
For such small values, you might want to display all values on one line, rather than on individual lines. You can accomplish this with end:
>>> for number in range(10):
... print(number, end=" ")
...
0 1 2 3 4 5 6 7 8 9 >>>
Note that your prompt slid back up into the output line again because you’re not using a newline as the output terminator. By calling print() without any arguments just after the loop, you can avoid that, too:
>>> for number in range(10):
... print(number, end=" ")
... print()
...
0 1 2 3 4 5 6 7 8 9
>>>
When you don’t provide any values to print(), it outputs a newline character, effectively moving the cursor to the next line. Alternatively, you can achieve the same effect with a bit of logic wrapped in a conditional expression:
>>> for number in range(10):
... print(number, end=(" " if number < 9 else "\n"))
...
0 1 2 3 4 5 6 7 8 9
>>>
Just like with sep, you can use any string as an argument to the end keyword, but some strings will make more sense than others as output terminators.
The print() function accepts two additional keyword arguments, file and flush, both of which affect how the function handles the output stream. If you want to learn how to work with these two additional keyword arguments, then you can read the in-depth guide about Python’s print() function.
Remove ads
Conclusion
Now you know how to handle basic input and output operations in Python using the input() and print() functions. You’ve explored how to gather user input from the keyboard, process that input, and display it back to the user in a meaningful way. Additionally, you delved into some advanced features of the print() function, such as formatting output with separators and controlling the newline character.
Understanding input and output is crucial for any Python developer, as these operations form the backbone of interacting with users and external systems. Knowing how to work with these tools allows you to create programs that are interactive, user-friendly, and capable of handling real-world data processing tasks.