Text
stringlengths
1
9.41k
We often refer to this interaction as taking place within the console.
The console is just a window where we receive text prompts, and reply by typing at the keyboard. This has a similar feel to the Python shell: prompt then reply, prompt then reply. ###### 7.3 The input() function Python makes it relatively easy to get input from the console, using the built-in function input().
The input() function takes a single, optional ----- parameter—a string—which, if supplied, is used as a prompt displayed to the user. Here’s a quick example at the Python shell: ``` >>> input("What is your name?
") What is your name? Sir Robin of Camelot 'Sir Robin of Camelot' >>> input("What is your favorite color? ") What is your favorite color?
Blue 'Blue' >>> input("What is the capital of Assyria? ") What is the capital of Assyria? I don't know that! "I don't know that!" input() takes a string as an argument.
This string is displayed as a ``` prompt to the user, like “How old are you?” or “How many cookies would you like to bake?” or “How long are your skis (in cm)?” After displaying a prompt, input() waits for the user to enter something at the keyboard. When the user hits the return key, input() returns what the user typ...
") What is your name? Sir Robin of Camelot >>> users_name 'Sir Robin of Camelot' ``` Try this out on your own in the Python shell. Here’s what just happened.
On the first line (above) we called the input() function and supplied the string argument “What is your name? ”. Then, on the second line, input() does its work.
It prints “What is your name?” and then waits for the user to type their response. In this case, the user has typed “Sir Robin of Camelot”.
When the user hits the enter/return key, the input() function returns what the user typed (before hitting enter/return) as a string.
In this example, the string returned by input() is assigned the name users_name.
On the third line, we enter the expression users_name and Python obliges by printing the associated value: “Sir Robin of Camelot”. Here’s a short program that prompts the user for their name and their quest, and just echoes back what the user has typed: ----- ``` """Prompts the user for their name and quest and ...
""" name = input('What is your name? ') quest = input('What is your quest? ') print(name) print(quest) ``` Try it out.
Copy this code, paste it into an editor window in your text editor or IDE, and save the file as name_and_quest.py. Then run the program.
When run, the program first will prompt the user with ‘What is your name? ’ and then it will assign the value returned by input() to the variable name.
Then it will prompt for the user’s quest and handle the result similarly, assigning the result to the variable quest.
Once the program has gathered the information it needs, it prints the name and quest that the user provided. A session for this might look like this: ``` What is your name?
Galahad What is your quest? To seek the Holy Grail! Galahad To seek the Holy Grail! ``` Notice that in order to use the strings returned by input() we assigned them to variables.
Again, remember that the input() function returns a string. That’s pretty convenient, when what we want are strings, but sometimes we want numeric data, so we’ll also learn how to convert strings to numeric data (where possible) with the functions int() and float(). ###### 7.4 Converting strings to numeric types The...
We’ll get the message: ``` TypeError: can't multiply sequence by non-int of type 'float' ``` What happened?
When the program gets input from the user: ``` kg = input("Enter the weight in kilograms (kg): ") ``` the value returned from the input() function is a string.
The value returned from the input() function is always a string. Say the user enters “82” at the prompt.
Then what gets saved with the name kg is the string ``` '82' not the number 82 and we can’t multiply a string by a floating point ``` number—that makes no sense! Happily, there’s an easy fix.
Python provides built-in functions that can be used to produce objects of numeric types from a string (if possible). These are the integer constructor, int(), and the float constructor, ``` float().
These functions can take a string which looks like it ought to be ``` convertible to a number, performs the conversion, and returns an object of the corresponding numeric type. Let’s try these out in the Python shell: ``` >>> int('82') 82 >>> float('82') 82.0 ``` In the first instance, we pass the string '82'...
In the second instance, we pass the string '82' as an argument to the float() constructor to get a float. ``` What happens if have a string like '82.5'?
This is a valid input to the float() constructor, but does not work with the int() constructor. ``` >>> float('82.5') # this works OK 82.5 >>> int('82.5') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '82.5' ``` The error message...
This expression is evaluated from the inside out (as you might suspect). First the call to input() displays the prompt provided, waits for input, then returns a string.
The value returned (say, '82.5') is then passed to the float constructor as an argument. The float constructor does its work and the constructor returns a floating point number, ``` 82.5.
Now, when we pass this value to the function kg_to_pounds(), ev ``` erything works just fine. If you’ve seen mathematical functions before this is no different from something like 𝑓(𝑔(𝑥)) where we would first calculate 𝑔(𝑥) and then apply 𝑓 to the result. ###### Another scenario with a nasty bug Consider this...
""" a = input("Enter an integer: ") b = input("Enter another integer: ") print(a + b) ``` Can you see what the bug is? Imagine what would happen if at the first prompt the user typed “42” and at the second prompt the user typed “10”.
Of course, 42 plus 10 equals 52, but is that what this program would print? No.
Here’s a trial run of this program: ``` Enter an integer: 42 Enter another integer: 10 4210 ``` ----- “4210” is not the correct result!
What happened? Remember, input() always returns a string, so in the program above, ``` a is a string and b is a string.
Thus, when we perform the operation a + b it’s not addition, it’s string concatenation! ``` What do we do in cases like this?
In order to perform arithmetic with user-supplied values from input(), we first need to convert input strings to numeric types (as above). ``` """This program fixes the bug in the earlier program.""" a = input("Enter an integer: ") b = input("Enter another integer: ") a = int(a) b = int(b) print(a + b) ```...
For example, if a misbehaved user were to enter values that cannot be converted to integers, we might see a session like this: ``` Enter an integer: cheese Enter another integer: bananas Traceback (most recent call last): File "/myfiles/addition_fixed.py", line 5, in <module> a = int(a) ValueError: inval...
In this case, Python reports a ValueError and indicates the invalid literal ``` 'cheese'.
We’ll see how to handle problems like this later on in Chapter ``` 15. ``` input() does not validate input ``` It’s important to note that input() does not validate the user’s input. ----- _Validation is a process whereby we check to ensure that input from a_ user or some other source meets certain criteria.
That’s a big topic we’ll touch on later, but for now, just keep in mind that the user can type just about anything at a prompt and input() will return whatever the user typed—without checking anything. So a different session with the same program (above) might be ``` What is your name?
-1 -1 ``` Be warned. ###### Don’t use names that collide with names of built-in Python functions! As noted, input, int, and float are names of built-in Python functions. It’s very important that you do not use such names as names for your own functions or variables.
In doing so, for example, you’d be reassigning the name input, and thus the input() function would no longer be accessible. For example, this ``` input = input('What is your name?
') print(input) # so far, so good -- prints what the user typed input = input('What is your quest?
') print(input) ``` fails miserably, with ``` Traceback (most recent call last): File ".../3.10/lib/python3.10/code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> TypeError: 'str' object is not callable ``` What happened?
We assigned the result to an object named input, so after the first line (above) is executed, input no longer refers to the function, but instead is now a string (hence the error message “ ‘str’ object is not callable”). So be careful to choose good names and avoid collisions with built-ins. ###### Additional resource...
If it makes your head spin, just navigate away and move on. But maybe the documentation can deepen your understanding of these functions.
See relevant sections of: [• https://docs.python.org/3/library/functions.html](https://docs.python.org/3/library/functions.html) ----- ###### 7.5 Some ways to format output Say we want to write a program which prompts a user for some number and calculates the square of that number.
Here’s a program that does just that: ``` """A program to square a number provided by the user and display the result.
""" x = input("Enter a number: ") x = float(x) result = x * x print(result) ``` That’s fine, but perhaps we could make this more friendly.
Let’s say we wanted to print the result like this. ``` 17.0 squared is 289.0 ``` How would we go about it? There are a few ways. One somewhat clunky approach would be to use string concatenation.
Now, we cannot do this: ``` """A program to square a number provided by the user and display the result.
""" x = input("Enter a number: ") x = float(x) result = x * x print(x + ' squared is ' + result) ``` This program fails, with the error: ``` Traceback (most recent call last): File ".../squared_with_concatenation.py", line 4, in <module> print(x + ' squared is ' + result) TypeError: unsupported oper...
Because we cannot concatenate floats and strings.
One way to fix this would be to explicitly convert the floating-point values to strings. We can do this—explicitly—by using Python’s built-in function str(). ``` """A program to square a number provided by the user and display the result.
""" x = input("Enter a number: ") x = float(x) result = x * x print(str(x) + ' squared is ' + str(result)) ``` Now, this works.
Here’s a trial. ----- ``` Enter a number: 17 17.0 squared is 289.0 ``` Again, this works, but it’s not a particularly elegant solution.
If you were to think “there must be a better way” you’d be right! ###### 7.6 Python f-strings and string interpolation The approach described above is valid Python, but there’s a better way. Earlier versions of Python offered a form of string interpolation borrowed from the C programming language and the string forma...
These are still available, but are largely superseded. With Python 3.6 came f-strings.[1] f-strings provide an improved approach to string interpolation.
They are, essentially, template strings with placeholders for values we wish to interpolate into the string. An f-string is prefixed with the letter f, thus: ``` f'I am an f-string, albeit a boring one.' ``` The prefix tells the Python interpreter that this is an f-string. Within the f-string, we can include names o...
For example,_ ``` >>> name = 'Carol' >>> f'My name is {name}.' My name is Carol. >>> favorite_number = 498 >>> f'My favorite number is {favorite_number}.' My favorite number is 498. >>> f'My favorite number is {400 + 90 + 8}.' My favorite number is 498. ``` Here’s how we’d solve our earlier problem abo...
""" x = input("Enter a number: ") x = float(x) result = x * x print(f'{x} squared is {result}') ``` 1“F-string” is short for “formatted string literal”. These were introduced in Python 3.6.
For details, see the Input and Output section of the official Python [tutorial (https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-](https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-literals) [literals), and PEP 498 (https://peps.python.org/pep-0498/) for a complete ratio-](https:/...
The decimal expansion of this is 0.333… Let’s print this. ``` >>> 1 / 3 0.3333333333333333 ``` Now, in this example, it’s unlikely that you’d need or want to display 0.3333333333333333 to quite so many decimal places.
Usually, it suffices to print fewer digits to the right of the decimal point, for example, 0.33 or 0.3333.
If we were to interpolate this value within an f-string, we’d get a similar result. ``` >>> x = 1 / 3 >>> f'{x}' '0.3333333333333333' ``` Fortunately, we can tell Python how many decimal places we wish to use.
We can include a format specifier within our f-string. ``` >>> x = 1 / 3 >>> f'{x:.2f}' '0.33' ``` The syntax for this is to follow the interpolated element with a colon ``` : and then a specifier for the desired format.
In the example above, we ``` used .2f meaning “display as a floating-point number to two decimal places precision”.
Notice what happens here: ``` >>> x = 2 / 3 >>> f'{x:.2f}' '0.67' ``` Python has taken care of rounding for us, rounding the value 0.6666666666666666 to two decimal places.
Unless you have very specific reasons not to do so, you should use f-strings for formatting output. There are many format specifiers we can use.
Here are a few: ###### Format a floating-point number as a percentage. ``` >>> x = 2 / 3 >>> f'{x:.2%}' '66.67%' ``` ----- ###### Format an integer with comma-separated thousands ``` >>> x = 1234567890 >>> f'{x:,}' '1,234,567,890' Format a floating-point number with comma-separated thousands >>> gdp...
For this, we need to be able to specify width of a field or column, and the alignment of a field or column.
For example, say we wanted to print a table like this:[2] ``` GDP Population GDP per Country ($ billion) (million) capita ($) ---------------------------------------------------- Chad 11.780 16.818 700 Chile 317.059 19.768 16,039 China 17,734.063 1,412.600 12,554 Colombia 314.323 51.049 6,157 ...
We’ll start with the column headings. [2Sources: 2021 GDP from World Bank (https://data.worldbank.org/); 2021](https://data.worldbank.org/) [population from the United Nations (https://www.un.org/development/desa/pd/).](https://www.un.org/development/desa/pd/) ----- ``` print(f'{"":<12}' f'{"GDP":>16}' ...
> is used for right-alignment ``` (it points right).
The numbers in the format specifiers (above) designate the width of the field (or column), so the country column is 12 characters wide, GDP column is 16 characters wide, etc. Now let’s see about a horizontal rule, dividing the column headings from the data.
For that we can use repeated concatenation. ``` print('-' * 60) # prints 60 hyphens ``` So now we have ``` print(f'{"":<12}' f'{"GDP":>16}' f'{"Population":>16}' f'{"GDP per":>16}') print(f'{"Country":<12}' f'{"($ billion)":>16}' f'{"(million)":>16}' f'{"capita ($)":>16}') p...
Let’s say we have the data in this form: 3This takes advantage of the fact that when Python sees two strings without an operator between them it will concatenate them automatically.
Don’t do this just to save keystrokes.
It’s best to reserve this feature for handling long lines or building long strings across multiple lines. ----- ``` gdp_chad = 11.780 gdp_chile = 317.059 gdp_china = 17734.063 gdp_colombia = 314.323 pop_chad = 16.818 pop_chile = 19.768 pop_china = 1412.600 pop_colombia = 51.049 ``` (Yeah.
This is a little clunky.
We’ll learn better ways to handle data later.) We could print the rows in our table like this: ``` print(f'{"Chad":<12}' f'{gdp_chad:>16,.3f}' f'{pop_chad:>16,.3f}' f'{gdp_chad / pop_chad * 1000:>16,.0f}') print(f'{"Chile":<12}' f'{gdp_chile:>16,.3f}' f'{pop_chile:>16,.3f}' f'{gd...
This is a little clunky too.
We’ll see better ways soon.) Notice that we can combine format specifiers, so for values in the GDP column we have a format specifier ``` >16,.3f ``` The first symbol > indicates that the column should be right-aligned.
The ``` 16 indicates the width of the column. The, indicates that we should use ``` a comma as a thousands separator.
.3f indicates formatting as a floating point number, with three decimal places of precision.
Other format specifiers are similar. Putting it all together we have: ``` gdp_chad = 11.780 gdp_chile = 317.059 gdp_china = 17734.063 gdp_colombia = 314.323 ``` ----- ``` pop_chad = 16.818 pop_chile = 19.768 pop_china = 1412.600 pop_colombia = 51.049 print(f'{"":<12}' f'{"GDP":>16}' f'{...
Consider how we’d like such a program to behave, assuming we need the exchange rate as a user-supplied input.
What’s the information we’d need to perform the calculation? - The amount we’d like to convert. - A label for the currency we’d like to convert, for example, USD, CAD, MXN, BRL, EUR, etc.[4] We’ll call this the source currency. - An exchange rate. - A label for the currency we want to receive (as above).
We’ll call this the target currency. Let’s imagine how this might work: 1. The user is prompted for a source currency label. 2. The user is prompted for a target currency label. 3.
The user is prompted for an amount (in the source currency). 4. The user is prompted for an exchange rate. 5.
The program displays the result. This raises the question: how do we express the exchange rate?
One approach would be to express the rate as the ratio of the value of the source currency unit to the target currency unit.
For example, as of this writing, one US dollar (USD) is equivalent to 1.3134 Canadian dollars (CAD). Taking this approach, we’ll multiply the source currency amount by the exchange rate to get the equivalent value in the target currency. Here’s how a session might proceed: ``` Enter source currency label: USD Enter...
We will convert USD to CAD. Enter the amount in USD you wish to convert: 1.00 Enter the exchange rate (USD/CAD): 1.3134 1.00 USD is worth 1.31 CAD ``` At this point, we don’t have all the tools we’d need to validate input from the user, so for this program we’ll trust the user to be well-behaved and to enter rea...
(We’ll see more on input validation and exception handling soon.) With this proviso, here’s how we might start this program: ``` source_label = input('Enter source currency label: ') target_label = input('Enter target currency label: ') print(f'OK.
We will convert {source_label} ' f'to {target_label}.') ``` This code will prompt the user for source and target labels and then print out the conversion the user has requested.
Notice that we use an f-string to interpolate the user-supplied labels. [4For three-character ISO 4217 standard currency codes, see: https://en.wikiped](https://en.wikipedia.org/wiki/ISO_4217) [ia.org/wiki/ISO_4217.](https://en.wikipedia.org/wiki/ISO_4217) ----- Now we need two other bits of information: the amount...
(Here we’ll use the \, which, when used as shown, signifies an explicit line continuation in Python.
Python will automatically join the lines.)[5] ``` source_prompt = f'Enter the amount in {source_label} ' \ f'you wish to convert: ' ex_rate_prompt = f'Enter the exchange rate ' \ f'({source_label}/{target_label}): ' source_amount = float(input(source_prompt)) exchange_rate = float(input(...
The labels are of type str.