Chapter 3

Strings & Input

Subsections of Strings & Input

Input

YouTube Video

Resources

The Python programs we’ve written up to this point are very static - each time we run the program, it will perform the same exact operations. Since we’re running these programs on a real computer, it might be helpful to build programs that can read and respond to input from the user, making them much more useful overall. Python includes many different ways to handle user input, but in this lab we’ll just focus on the simple input() function.

Input in Python

The input() function is used to display a prompt the user and then record input. Let’s look at a quick example:

name = input("Enter your name: ")
print("Hello ", end="")
print(name)

Here, we see that the input() function actually accepts a message as an argument, which will be displayed to the user. After the message is printed, the user will be given a cursor to enter text immediately after it. Once the user presses the ENTER key, the input() function will read the input that was entered and store it as a string value or str data type in the variable called name.

For example, if the user inputs Willie Wildcat at the prompt, this program’s output will look like this:

Enter your name: Willie Wildcat
Hello Willie Wildcat

We can see this even more clearly in the terminal. When we first run the program, we’ll see the prompt "Enter your name:" printed, followed by a cursor prompting the user to enter something:

Terminal Before Input Terminal Before Input

Once the user types the input and presses ENTER, the rest of the program will run:

Terminal Before Input Terminal Before Input

Now we see the cursor is at the next command prompt, ready to run another program.

Subsections of Input

Numerical Input

YouTube Video

Resources

Of course, we can also read numerical input in Python using the input() function. To do this, we must simply use either the int() or float() function to convert the input received as a string to the correct data type.

Here’s a quick example program that requires two inputs for the price and quantity of an item being purchased:

text_one = input("Enter the price of one item: ")
price = float(text_one)
text_two = input("Enter the quantity of items: ")
quantity = int(text_two)
cost = price * quantity
print("The total cost is $", end="")
print(cost)

If the user wishes to purchase $ 3 $ items at the price of $ 2.75 $ per item, then the program’s output would look like this:

Enter the price of one item: 2.75
Enter the quantity of items: 3
The total cost is $8.25

In the program, we simply read each input from the user as a string value, then use the appropriate conversion function to convert it to the correct data type. For numbers including a decimal point, we use float(), but for whole numbers we use the int() function.

This works well if the user enters values that make sense. But, what if the user wishes to purchase a fraction of an item? Will this program work? Unfortunately, if the user enters a value with a decimal point for the second input, it can no longer be converted to an integer and we’ll get an error:

Enter the price of one item: 2.75
Enter the quantity of items: 3.5
Traceback (most recent call last):
  File "tutor.py", line 4, in <module>
    quantity = int(text_two)
ValueError: invalid literal for int() with base 10: '3.5'

For right now, there’s not much we can do about that error other than write programs that clearly tell the user what type of data is expected, but later we’ll learn how to handle errors like this and prompt the user for input again.

Subsections of Numerical Input

String Operators

YouTube Video

Resources

Concatenate

Python includes an operator that can be used to concatenate, or combine, two strings together, one after another. We can use the plus symbol + between two strings to concatenate them together into a single string, making it much simpler to build more complex strings and outputs.

A simple example is shown below:

first = "Hello"
second = "World"
print(first + second)

When executed, this code will display this output:

HelloWorld

As we can see, using the + operator in Python to concatenate two strings together is a quick and easy way to simplify our print statements.

Concatenating Numbers

Python also requires both sides of the + operator to be strings in order for concatenation to work. So, if we want to concatenate a string with a numeric value, we’ll have to convert it to a string using the special str() function. Here’s an example:

text = "Your total is $"
value = 2.75
print(text + str(value))

When we run this program, we’ll receive the following output:

Your total is $2.75

However, if we forget to convert the value variable to a string, as in this example:

text = "Your total is $"
value = 2.75
print(text + value)

we’ll receive an error instead:

Traceback (most recent call last):
  File "tutor.py", line 3, in <module>
    print(text + value)
TypeError: must be str, not float

So, we’ll have to be careful and make sure that we convert all of our numbers to strings before trying to concatenate them together. Of course, if both sides of the + operator are numbers, then it will perform addition instead of concatenation!

Repeat

Python also includes an operator that allows us to quickly repeat strings. We can use the asterisk * operator to effectively “multiply” a string. Consider this example:

word = "repeat"
print(word * 2)
print(word * 4)

When we run this program, we’ll see the following output:

repeatrepeat
repeatrepeatrepeatrepeat

This allows us to build outputs that consist of repeated strings. We can also use this to quickly format our output into various shapes and structures!

Escape

Finally, we can also use the escape operator \ to handle some certain special characters in Python strings. We’ve already seen this used in the newline character, which is simply the escape operator \ followed by the letter n, as in \n.

However, we can also use it to include quotation marks in our string itself. Consider the following example:

sentence = "Hello from "the little apple!""
print(sentence)

When we try to run this code, we’ll get the following error:

  File test.py, line 1
    sentence = "Hello from "the little apple!""
                            ^
SyntaxError: invalid syntax

This is because the double quotation mark " is used to show which part of the code is a string value, but the Python interpreter gets confused when we try to include quotation marks inside of our strings. So, we can use the escape operator \ to tell it to treat those quotation marks as part of the string value itself, and not part of the Python code:

sentence = "Hello from \"the little apple!\""
print(sentence)

This program will execute properly and produce the following output:

Hello from "the little apple!"

Notice that the quotation marks now appear correctly in the output, but the escape operators are not shown. There are many other special ways to use the escape operator in Python, all of which can be found in the Python Documentation.

Single and Double Quotes

Python also allows us to mix single and double quotes in a string, as long as we use them consistently, So, we can change the previous example to use single quotes around the string itself, and remove the escape operator from the double quotes, which will result in this code:

sentence = 'Hello from "the little apple!"'
print(sentence)

This code will also produce the desired output. However, in this class we won’t use single quotes around strings, just for consistency. Many other programming languages don’t allow this, so we encourage you to learn how to use the escape operator to handle these situations.

Subsections of String Operators

F-Strings

YouTube Video

Resources

Python also includes another method of building strings, which are known as “F-strings”. F-strings allow us to put placeholders in strings that are later replaced with values from variables, effectively creating a way to build “templates” that can be used throughout our program.

The easiest way to see how this works is looking at a few examples. Let’s start with a simple one:

name = input("Enter your name: ")
print(f"Hello {name}")

If the user inputs "Willie Wildcat" when prompted, then this code will produce this output:

Enter your name: Willie Wildcat
Hello Willie Wildcat

There are many important parts to this example, so let’s look at each one individually. First, in the print() statement, we see the string "Hello {name}". This is an example of a template string, which includes a set of curly braces {} as placeholders for data to be inserted. Each template string can have unlimited sets of curly braces. Inside of each set of curly braces, we can place the variable or expression that will be printed at that location.

Also, we notice that in front of the string, we see the character f. Preceding a string with f outside of the quotation marks will denote the string as an f-string (hence the name), which allows the values inside to be interpolated. Interpolation is the term used when formatting marks in a string, such as the curly braces in an f-string, are interpreted and replaced with the correct values they represent.

Advanced Formatting

Python f-strings can do many powerful things, such as handle more complex formatting and multiple lines. For right now, we’ll just use simple variable placeholders in our f-strings, but over time we’ll introduce additional ways to use f-strings to achieve the desired output.

The most powerful use of f-strings is to insert numerical values directly into strings without having to convert each value directly to the str data type - the interpolation process handles this for us.

For example, we can update our previous program to use f-strings to display the output in a single print() statement, and we can also add additional information with ease:

text_one = input("Enter the price of one item: ")
price = float(text_one)
text_two = input("Enter the quantity of items: ")
quantity = int(text_two)
cost = price * quantity
print(f"{quantity} items at ${price} each is ${cost} total")

When we execute this program, we’ll see output that looks like this:

Enter the price of one item: 2.75
Enter the quantity of items: 3
3 items at $2.75 each is $8.25 total

This example shows how easy it is to build complex output strings using f-strings.

Format Method

Prior to the introduction of f-strings, it was common to use the format() method to place values inside of a template string. The last line of the previous example would look like this using the format method:

print("{} items at ${} each is ${} total".format(quantity, price, cost))

As we can see, the format() method receives each value as an argument, and it will replace the curly brace placeholders {} in the template string with each value, working from left to right. The output produced will be identical to the f-string in the example above.

We won’t use the format() method in this class, but you may see it in many online tutorials and documentation since f-strings were introduced relatively recently.

Subsections of F-Strings

Complex Statements

YouTube Video

Resources

Finally, let’s look at how we can rewrite some of our previous Python programs by combining expressions into more complex statements. Python allows us to perform multiple actions on a single line of code, provided they can all be combined in some way to create a single statement.

Let’s consider the example on the previous page, shown here:

text_one = input("Enter the first number: ")
one = int(text_one)
text_two = input("Enter the second number: ")
two = int(text_two)
one = one * one
two = two * two
total = one + two
print(f"The sum of squares of {one} and {two} is {total}")

There are many ways we can write this program to perform the same work. For example, the process of computing the sum of squares itself can actually be reduced to a single line of code as seen below:

total = (one * one) + (two * two)

We can perform multiple mathematical operations in a single expression, and as long as we either use parentheses or pay attention to the order of operations, we’ll get the expected answer. We don’t have to store the intermediate values in variables, since Python will do that for us when it evaluates the expression.

Likewise, we can put the input() function inside of the int() function, allowing us to read input as a string and convert it to an integer in a single line:

one = int(input("Enter the first number: "))
two = int(input("Enter the second number: "))
total = (one * one) + (two * two)
print(f"The sum of squares of {one} and {two} is {total}")

Finally, we can also move the computation of the sum of squares directly into the f-string. When Python tries to print the f-string, the interpolation process must compute that value before it can print the output.

one = int(input("Enter the first number: "))
two = int(input("Enter the second number: "))
print(f"The sum of squares of {one} and {two} is {(one * one) + (two * two)}")

Functionally, this code will create the exact same output as the previous code, but it will do so using fewer variables and statements. Each statement is simply more complex, consisting of multiple expressions.

Concise and Readable

The real question is: which of these two examples is best? That is, which one is the preferred coding style to learn? The answer is that it really depends - both have their merits, and functionally they will work nearly identically on most modern computers and programming languages.

It really is a question of style - is it better to have more lines of code and variables, clearly spelling out what each step of the process is, or is it better to have shorter programs with more complex lines of code but maybe fewer variables? For beginning programmers, it is usually recommended to follow the first style, using as many variables as needed and focusing on short, concise lines of code over large, complex statements.

However, as we become more accustomed to programming, we’ll find that many times it is easier to read and understand complex statements, and our code can be written in a way that better reflects what it is actually doing.

This is very similar to learning how to read, write, and speak in a new language. We must start with short, concise sentences, and slowly build up our knowledge of more complex statements and grammar rules until we become a fluent speaker.

Overall, the best advice to follow is to make your code readable to both yourself and anyone else who may have to read and maintain the code. As long as it is clear what the code is doing based on what it says, it is probably a good style to follow. As we continue to learn more, we’ll slowly refine our coding style to be one that is easy to follow and understand for everyone.

Subsections of Complex Statements

Input Practice

Let’s try some simple practice problems. These problems are not graded - they are just for you to practice before doing the real exercises in the lab itself. You can find the answers below each question by clicking the button below each question.

3.1 Reading Code

Write the output that is displayed to the user after running the following Python code:

x = input("Enter a number: ")
y = x + "00"
z = int(y)
a = int(z + (z / 100))
print(f"The result is {a}")

Assume the user inputs the string "4" when prompted.

3.1 Answer

The correct answer is:

The result is 404

3.2 Reading Code

Write the output that is displayed to the user after running the following Python code:

x = int(input("Enter a number: "))
x = x // 100 * 100 + x % 10
print(f"The answer twice is {x * 2}")

Assume the user inputs the string "121" when prompted.

3.2 Answer

The correct answer is:

The answer twice is 202

Notice that the x * 2 expression results in the value 202 instead of the string "101101". This is because x is an integer value, not a string. So, the * operator is interpreted as multiplication, not string repetition. We have to carefully keep track of what data type each variable is storing in order to truly understand what the code will do.

3.3 Writing Code

Write a Python program that prompts the user to input a verb and a noun that will be stored in separate variables. Then, use those two words to create a simple compliment for the user and print it to the terminal. The compliment should be in the form of:

You "<verb>" my "<noun>"? That's awesome!

For example, if the user inputs "love" and "food", then the string printed by the program should be:

You "love" my "food"? That's awesome!

Hint: Notice that the output includes quotation marks around the two words provided by the user, and an apostrophe (single quote) as well. You’ll need to account for this in your code!

You can expand on this program to prompt the user for additional inputs, and use f-strings to create a Mad Libs style game!

3.3 Answer

One possible answer is:

verb = input("Enter a verb: ")
noun = input("Enter a noun: ")
print(f"You \"{verb}\" my \"{noun}\"? That's awesome!")

The biggest point to remember is that quotation marks need to be escaped. If you try to use single quotes instead of double quotes around the f-string, you’ll need to escape the apostrophe (single quote) instead.

Summary

Python input

  • input(expression) will display the expression to the user as a prompt, then return what was typed by the user as a string value.
  • input(expression) is terminated by the user pressing ENTER, so next output starts on a new line.

Python String Operators

  • + Concatenation (join strings together). May only be applied to two strings.
  • * Repeat (duplicate strings)
  • \ Escape Operator for special characters
  • f-string are used to format output. Template strings include curly braces as placeholders {} and inside the placeholder is any variable or expression to be printed in that location in the template string.

Complex Statements

Expressions can be combined in many ways within a statement. Expressions can be used as arguments to functions, and more!