Back Python Chrestomathics Ahead |
Part 4 — Interactivity
Communicating — Back and forth is a means — Brings needed knowledge
Section 4.1: Function input()
- Our previous programs introduced important programming concepts — but they were not problem solvers. They produced the exact same output every time they were run.
- Programs that truly problem solve, get user input, and then use the input to solve the problem of interest. Such programs are interactive as their code reacts to the needs of the program user.
- Python has a built-in function input() that will read and then return, the next line of user input. The
input()
function always, always, always returns the user reply as a string, regardless of what was entered.
reply = input( "Enter text: " )
- The function can act with either no arguments or a single string argument. For all our uses, we will supply a string, called the prompt, that clues the reader what the program needs to complete its task.
- The
input()
function displays the prompt without a newline character being printed. Once supplying the prompt, the program pauses until the user enters their reply.
- The above
input()
statement comes from program echo.py. The program gets two inputs from the user and then echoes them back out.
""" Purpose: demonstrate string acquisition (the getting of input)
"""
# Get and echo back first input
reply = input( "Enter text: " )
print( "You replied:", reply )
print()
# Get and echo back second input
reply = input( "Enter more text: " )
print( "You then replied:", reply )
- Both uses of
input()
include a trailing space at the end of the prompt. That space is important. It causes a visual separation between the prompt and the input.
- Below is a possible user-program interaction. In our depictions of program runs, the inputs will be boxed.
Enter text: Tell me a secret
You replied: Tell me a secret
Enter more text: What is your name
You then replied: What is your name
- Let’s trace through this program run. If the user entered Tell me a secret, then the
input()
function returns the string"Tell me a secret"
. That string is assigned to variablereply
.
Variable | Value |
reply | "Tell me a secret" |
- The program then prints the literal
"You replied"
and the value of variablereply
.
You replied: Tell me a secret
- If in reaction to the second use of function
input()
, the user replies What is your name, then variablereply
would be updated to"What is your name"
.
Variable | Value |
reply | "What is your name" |
- Causing the
print()
statement to then display.
You then replied: What is your name
- Here is another possible program interaction. It is important to give your complete attention on the values variable
reply
takes on.
Enter text: 88
You replied: 88
Enter more text:
You then replied:
- If the user enters 88 in reaction to the first prompt, then variable
reply
is assigned the string value"88"
and not the integer 88. Why, because theinput()
function always returns a string, no matter the reply.
Variable | Value |
reply | "88" |
- You must try hard to remember this fact. Not remembering is a frequent problem for many beginning Python programmers.
- If in reaction to the second prompt, the user simply enters without any other text, then variable
reply
is assigned the string value""
. We call this string the empty string. The empty string is a string of length 0.
Variable | Value |
reply | "" |
Section 4.2: Function len()
- Python has a versatile built-in function named len() that can work with a string. With a string argument, the function returns the number of characters in the string. Let’s look at program character_count.py, to see it in action.
# Get input
reply = input( "Enter text: " )
# Process the input
count = len( reply )
# Print the results
print( reply, "has", count, "characters" )
- The program line of interest is
count = len( reply )
- Function
len()
examines the value of its string argumentreply
and counts the number of characters in the string. The count includes all characters including whitespace and punctuation.
- Below are three possible program runs. Each run processes a single string.
Enter text: go your own way
go your own way has 15 characters
Enter text: strengths
strengths has 9 characters
Enter text: scraunched
scraunched has 10 characters
Section 4.3: Processing numeric inputs
- We now consider program being_powerful.py. The program separately prompts the user for an integer number
x
and a decimal numbern
. The program computes and displaysx
n
.
# Get inputs
x_reply = input( 'Enter base x (integer): ' )
n_reply = input( 'Enter exponent n (decimal): ' )
print()
# Massage input to numeric
x = int( x_reply ) # cast string get an int
n = float( n_reply ) # cast string get a decimal
# Compute result -- x to the nth power
result = x ** n
# Display result
print( result )
- The program has four parts that can serve as a template for much of our future problem solving.
- Get inputs
- Massage inputs into needed values
- Compute result
- Print result
- Because the inputs are being got separately, there are two uses of the
input()
function.
# Get inputs
x_reply = input( 'Enter base x (integer): ' )
n_reply = input( 'Enter exponent n (decimal): ' )
- Variables
x_reply
andn_reply
hold strings, but we need numeric values. So, we use the casting functionsint()
andfloat()
introduced with program cast_away.py.
# Massage input to numeric
x = int( x_reply ) # cast string get an int
n = float( n_reply ) # cast string get a decimal
- With the inputs now in a numeric form, the program can calculate its result using the Python exponentiation operator
**
.
# Compute result -- x to the nth power
result = x ** n
- Lastly, the program displays the result.
# Display result
print( result )
- Some possible program runs are below. In examining the interactions, remember Python decimal arithmetic approximates actual arithmetic.
Enter base (integer): 2
Enter exponent (decimal): 0.5
1.4142135623730951
Enter base (integer): 11
Enter exponent (decimal): 3.14
1861.971509290233
Enter base (integer): 4
Enter exponent (decimal): 0.333
1.5866676863822857
Section 4.4: Type str
It is not enough — Integers and decimals — We need a string type
- It is time to talk again about strings in Python. Because problem solving is more than doing numerical calculations, programming languages provide support for other types of values. For many programmers, their most-used type is their programming language’s string type. The Python string type is
str
.
- The Python string type has lots of handy features. We will start with string addition, or as it is called by programmers, concatenation.
- The
+
operator besides working when both its operands are numeric, also works when both its operands are strings. The result is a new string whose beginning is the left operand of the+
operator and whose end is the right operand of the+
operator. Consider the following code segment from daydreamer.py.
a = 'day'
b = 'dreamer'
c = a + b
print( a, '+', b, 'is', c )
- The segment outputs
day + dreamer is daydreamer
- The multiplication
*
will work when one of its operands is an integer and the other is a string. The operator produces a new string composed of multiple copies of the string operand. The number of copies is determined by the integer operand. The following code segment from dashes.py demonstrates string replication.
one_dash = "-"
n = 50
dashes = n * one_dash
print( n, "*", one_dash, "is", dashes )
dashes = one_dash * n
print( one_dash, "*", n, "is", dashes )
- The code twice uses the
*
operator to produce a string of fifty hyphens.
50 * - is --------------------------------------------------
- * 50 is --------------------------------------------------
- Python strings are viewed as objects. Just like with objects in the physical world, software objects can have attributes and behaviors. The attributes and behaviors of an object are called its members. For a string, its attribute is the character sequence being represented.
- Most software objects have behaviors that allow them to be queried, modified, and utilized. However, once a Python string is created, it cannot be modified. We say that strings are immutable.
- Interactions with software objects are done with special functions, called methods. A method is always used in tandem with an object. Without the object, there are no attributes to take into consideration.
- An object type that provides behaviors is called a class type.
- The Python string class provides dozens of methods to inspect and produce variants of a string. Our interest will concentrate on only a handful.
Section 4.5: String method split()
Something is lacking — A new perspective needed — Splitting can help out
- We start with string method
split()
. For now, we will use thesplit()
method without any arguments. The following statement is from program trio.py.
w1, w2, w3 = reply.split()
- The expression
reply.split()
applies methodsplit()
on stringreply
. The.
is the Python selection operator; it is informally called the dot operator. The operator needs an object to its left and a class member to its right.
- Method
split()
examines its string and returns a new list of the non-whitespace substrings that make up its string. In the below statement, those substrings are assigned respectively to string variablesw1
,w2
, andw3
.
w1, w2, w3 = reply.split()
- If variable
reply
represented the string" you me us "
then after the statement completes, its tracking would look like the following.
Variable | Value |
reply | " you me us " |
w1 | "you" |
w1 | "me" |
w1 | "us" |
- Be aware if the
reply
string does not have exactly three substrings, the statement cannot execute correctly, and your program will terminate.
- The complete program trio.py follows.
# Get input
reply = input( 'Enter three words: ' )
# Determine individual words w1, w2, and w3
w1, w2, w3 = reply.split()
# Display results
print()
print( "Your words:" )
print( w1 )
print( w2 )
print( w3 )
- Here are two possible program runs. It is left to you trace through the program with the different inputs.
Enter three words: peace joy friends
Your words
peace
joy
friends
Enter three words: ready or not
ready
or
not
Section 4.6: Pyramid power — case study
- A pyramid has a square base with four matching triangular faces that slope up from the base to meet at a common point.
- The surface area for a pyramid with height h and base perimeter p equals
- Program pyramid.py gets the two inputs from its user, and then computes and displays the surface area of the associated pyramid. The solution layout is like progam being_powerful.py.
- Get height and perimeter inputs
- Massage inputs into needed values
- Compute surface area
- Print result
- A possible program run could be
Enter pyramid height and its base perimeter: 24 56
Surface area: 700.0
- To get the two inputs, we will need an
input()
statement and then use the stringsplit()
method to break up the reply.
# Get height and perimeter inputs
reply = input( "Enter pyramid height and its base perimeter: " )
h, p = reply.split()
- A tracing of the program to this point would like
Variable | Value |
reply | "24 56" |
h | "24" |
p | "56" |
- These statements, leave
h
andp
in string form, but we need integer inputs. So, casting is required.
# Massage inputs into integers
h = int( h )
p = int( p )
- Most experienced Python programmers would have written the code using the below multi-assignment feature. In the earlier examples of a programming course, I prefer separate assignment statements like above.
h, p = int( h ), int( p )
- After the casting, our variables now look like
Variable | Value |
reply | "24 56" |
h | 24 |
p | 56 |
- The surface formula has a lot going on. So, our solution breaks up the calculation into two steps.
# Compute surface area
radical = ( h*h + ( p/8 * p/8 ) ) ** 0.5
surface = p / 2 * radical
- There are many other ways to code the formula; e.g., the inner pararentheses are not necessary. I chose to try to keep things clear without being too verbose.
- After the calculations, our variables now look like
Variable | Value |
reply | "24 56" |
h | 24 |
p | 56 |
radical | 25.0 |
surface | 700.0 |
- Once the result has been determined, we can print it out.
# Print result
print( "Surface area:", surface )
- Here are two more program runs. You are encouraged to trace through them on your own.
Enter pyramid height and its base perimeter: 15 64
Surface area: 544.0
Enter pyramid height and its base perimeter: 75 400
Surface area: 18027.756377319947
Section 4.7: Expression evaluation and operator precedence
- Our numerical expressions are starting to get a little more involved. It is worth some words to explain how Python evaluates expressions using multiple operators. You have likely seen from an algebra course, the quadratic equation
ax2 + bx + c
And also know how to evaluate it. The 2 in the equation is an exponent, and x2 is evaluated. The square is then multiplied by a. That value is added to the product bc. That sum is then added to c.
- Expression evaluation in Python mimics standard arithmetic evaluation. The important rules are loosely
- Exponentiation takes precedence over other arithmetic operators.
- Multiplication, division, and remaindering take precedence over addition and subtraction. If there are multiple multiplication, division, and remaindering operators they are done left to right.
- If there are multiple addition and subtraction operators they are done left to right.
- Terms with parentheses are evaluated as a unit.
- The complete rules for expression evaluator are given at python.org
- Let’s look at some programs that attempt to convert a Fahrenheit temperature f to its Celsius equivalent c. The scientific formula for temperature conversion is
- Generally, when people ask “What’s the temperature?”, they expect an integer value. So, our programs will expect an integer input and produce an integer output. This requirement means that sometimes the conversion is approximate.
- Consider program f_to_c_ver1.py. It uses the integer division operator.
# Get Fahrenheit input temperature f
reply = input( "Enter temperature (integer): " )
f = int( reply)
# Calculate integer Celsius equivelent
c = 5 // 9 * ( f - 32 )
# Display result
print( f, "°F equals", c, "°C" )
- Below are three program runs. They respectively use inputs 32, 212, and -40. I remember from high school science they convert to 0, 100, and -40.
Enter temperature (integer): 32
32 °F equals 0 °C
Enter temperature (integer): 212
212 °F equals 0 °C
Enter temperature (integer): -40
-40 °F equals 0 °C
- The first runs look good; but not the other two runs. What is wrong with the code? Before continue to read, think about it on your own.
- To figure out what’s going on, evaluate the assignment statement by hand.
c = 5 // 9 * ( f - 32 )
- What operation is evaluated first?
- Well?
- Another way to ask my question, what operator takes precedence?
- From the above discussion, we know division and multiplication has the highest precedence. And the leftmost of them is done first.
- So, what is the value of
5 // 9
?
- It’s zero. What is zero times anything, zero. So, no matter the value of
f
, the assignment makesc
, zero.
- How, can we fix it? Look at program f_to_c_ver2.py. It makes the division happen last.
# Get Fahrenheit input temperature f
reply = input( "Enter temperature (integer): " )
f = int( reply)
# Calculate integer Celsius equivelent
c = 5 * ( f - 32 ) // 9
# Display result
print( f, "°F equals", c, "°C" )
- Below are three program runs using the same inputs as above.
Enter temperature (integer): 32
32 °F equals 0 °C
Enter temperature (integer): 212
212 °F equals 100 °C
Enter temperature (integer): -40
-40 °F equals -40 °C
- All three runs look good.
- What is the moral of our example, be careful when developing expressions and remember that when division is involved thinks can get chaotic.
- Now look at program f_to_c_ver3.py. It does decimal division and converts the result to integer.
# Get Fahrenheit input temperature f
reply = input( "Enter temperature (integer): " )
f = int( reply)
# Calculate integer Celsius equivelent
c = 5/9 * ( f - 32 )
c = int( c )
# Display result
print( f, "°F equals", c, "°C" )
- Below are three program runs using the same inputs as above.
Enter temperature (integer): 32
32 °F equals 0 °C
Enter temperature (integer): 212
212 °F equals 100 °C
Enter temperature (integer): -40
-40 °F equals -40 °C
- All three runs look good.
- Which of the correct versions is better, that is up to you.
Section 4.8: What’s next
- To get the tools to clean up and inspect user-supplied data.
Back Python Chrestomathics Ahead |