Download this page as a jupyter notebook at Lesson 4

ENGR 1330 Computational Thinking with Data Science

Copyright © 2021 Theodore G. Cleveland, Farhang Forghanparast, and Mona Rizvi

Last GitHub Commit Date: 29 August 2021

Lesson 4 User Interaction:



Objectives

  1. Develop awareness of interactive inputs
  2. Implement interactive inputs to generalize solution tools
  3. Develop awareness of output formatting to improve readability
  4. Implement output formats

Input and Output

User Interaction

Until this point we have explicitly specified input values for variables (and constants) in a script; now lets leverage intrinsic functions that lets us makes use of variables. We’ll revisit earlier examples, but this time we’ll make them interactive. Instead of just computing and sending output, we want read into variables values that may change from time to time. In order to do that, our script needs to be able to prompt us for information and display them on the screen.

This whole process is the essence of user interaction, and from the simple examples herein, one builds more complex scripts.

Command-line input

About the input() function

Consider the script below

The input method sent the string 'What is your name ?' to the screen, and then waited for the user to reply. Upon reply, the input supplied was captured and then placed into the variable named MyName.

Then the next statement, used the print() method to print the contents of MyName back to the screen. From this simple structure we can create quite useful input and output.

As a matter of good practice, we should explicitly type the input variable, as shown below which takes the input stream and converts it into a string.

Below we prompt for a second input, in this case the user's age, which will be put into an integer. As a sdie note, we are not error checking, so if an input stream that cannot be made into an integer is suppplied we will get an exception warning or an error message.

More examples

Command-line output

About the print() function

The print() function is used to display information to users. It accepts zero or more expressions as parameters, separated by commas.

Consider the statement below, how many parameters are in the parameter list?

There are five parameters;

  1. "Hello World, my name is"
  2. MyName
  3. "and I am"
  4. MyAge
  5. "years old"

Three of the parameters are string literals and are enclosed in quote marks, two are variables that are rendered as strings.

Some more examples

About Strings

String Operators

Special and unprintable characters

Character Escape Sequence
newline \n
tab \t
backslash \\
quotes \' \"

About Escape Sequences

Sometimes we may need to print some special “unprintable” characters such as a tab or a newline. In this case, you need to use the \ (backslash) character to escape characters that otherwise have a different meaning. For instance to print a tab, we type the backslash character before the letter t, like this \t using our earlier example we have:

Here are a few more examples:

If you do not want characters preceded by the \ character to be interpreted as special characters, you can use raw strings by adding an r before the first quote. For instance, if you do not want \t to be interpreted as a tab in the string literal "Hello\tWorld", you would type

String slicing

Syntax Result
s[start] a single character
s[start:end] a substring
s[start:end:step] a selection of characters

Empty and default values in slicing

String functions

Name Behavior
s.split() Split a string into pieces based on a delimiter
s.strip() Remove leading/trailing whitespace or other characters
s.upper() Convert a string to uppercase
s.lower() Convert a string to lowercase
s.isnumeric() Return True if a string is numeric
s.find() Return the index of a substring
s.replace() Replace one substring with another
Many, many, more ... Look them up as needed

The % operator

Strings can be formatted using the % operator. This gives you greater control over how you want your string to be displayed and stored. The syntax for using the % operator is “string to be formatted” %(values or variables to be inserted into string, separated by commas)

An example using the string constructor (%) form using a placeholder in the print function call is:

Notice the syntax above. The contents of the two variables are placed in the locations within the string indicated by the %s symbol, the tuple (MyName,MyAge) is parsed using this placeholder and converted into a string by the trailing s in the %s indicator.

See what happens if we change the second %s into %f and run the script:

The change to %f turns the rendered tuple value into a float. Using these structures gives us a lot of output flexibility.

The %f formatter can also be used to place the decimal by preceeding the f with the decimal point and the number of digits after the decimal you want to render as in:

About the format() method

Similar to the %operator structure there is a format() method. Using the same example, the %s symbol is replaced by a pair of curly brackets {} playing the same placeholder role, and the format keyword precedes the tuple as

Observe the keyword format is joined to the string with a dot notation, because format is a formal method associated with all strings, and it is attached when the string literal is created.

In this example the arguments to the method are the two variables, but other arguments and decorators are possible allowing for elaborate outputs.

Triple quotes

If you need to display a long message, you can use the triple-quote symbol (‘’’ or “””) to span the message over multiple lines. For instance:

Future Versions

Readings

  1. Computational and Inferential Thinking Ani Adhikari and John DeNero, Computational and Inferential Thinking, The Foundations of Data Science, Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND) Chapters 3-6 https://www.inferentialthinking.com/chapters/03/programming-in-python.html

  2. LearnPython.org (Interactive Tutorial) (https://www.learnpython.org/) Short, interactive tutorial for those who just need a quick way to pick up Python syntax.

  3. Brian Christian and Tom Griffiths (2016) ALGORITHMS TO LIVE BY: The Computer Science of Human Decisions Henry Holt and Co. (https://www.amazon.com/Algorithms-Live-Computer-Science-Decisions/dp/1627790365)

  4. Learn Python in One Day and Learn It Well. Python for Beginners with Hands-on Project. (Learn Coding Fast with Hands-On Project Book -- Kindle Edition by LCF Publishing (Author), Jamie Chan https://www.amazon.com/Python-2nd-Beginners-Hands-Project-ebook/dp/B071Z2Q6TQ/ref=sr_1_3?dchild=1&keywords=learn+python+in+a+day&qid=1611108340&sr=8-3

  5. Learn Python the Hard Way (Online Book) (https://learnpythonthehardway.org/book/) Recommended for beginners who want a complete course in programming with Python.

  6. How to Learn Python for Data Science, The Self-Starter Way (https://elitedatascience.com/learn-python-for-data-science)

  7. String Literals https://bic-berkeley.github.io/psych-214-fall-2016/string_literals.html

  8. Tutorial on input() and print() functions https://www.programiz.com/python-programming/input-output-import