2.6 Reading input from the keyboard - Comprehensive Notes

Reading input from the keyboard

  • Programs commonly need to read input from the keyboard (user input). In Python, the built-in input() function is used to read data typed by the user.
  • The input() function reads a piece of data entered at the keyboard and returns that data as a string to the program. In formal terms: input()str\text{input}() \rightarrow \text{str}
  • Typical usage follows this general format:
    • Variable = input(prompt)
    • prompt is a string displayed on the screen to instruct the user what to enter.
    • After the user types and presses Enter, the data is returned as a string and assigned to the variable.
  • Example:
    • name = input("What is your name? ")
    • The prompt string (What is your name?) is shown, the program waits for input, and the entered data is assigned to the variable name as a string.
  • Interactive demonstration (conceptual):
    • name = input("What is your name? ")
    • User types: Holly
    • The string "Holly" is assigned to name
    • print(name) would display: Holly
  • Program examples that read multiple strings:
    • Example: read first and last name and greet the user
    • Steps: first_name = input("Enter your first name: ")
    • last_name = input("Enter your last name: ")
    • print("Hello,", firstname, lastname)
    • Transcript notes that the prompts often end with a space so the last character in the prompt is a space, visually separating the prompt from the user’s input. This is done because input() does not automatically print a trailing space.

Prompt strings and trailing space

  • The strings used as prompts in input() often end with a space (e.g., "Enter your first name ") so that, when the user starts typing, their input begins after a visible space following the prompt.
  • This practice avoids the last character of the prompt being directly attached to the user’s input on screen, improving readability.

Reading numbers with the input() function

  • The input() function always returns a string, even if the user enters numeric data. For example, if the user types 72, the returned value is the string "72".
  • To perform arithmetic, you must convert this string to a numeric type using conversion functions.
  • Built-in conversion functions:
    • int(x)\text{int}(x) converts the value of x to an integer.
    • float(x)\text{float}(x) converts the value of x to a float.
  • Summary table (data conversion):
    • Function: int\text{int} — Description: converts to an integer
    • Function: float\text{float} — Description: converts to a floating-point number
  • Payroll example (demonstrates conversion): read hours as input and convert to int
    • Traditional two-step approach (less efficient):
    • string_value = input("How many hours did you work? ")
    • hours = int(string_value)
    • Better one-step approach (nested function calls):
    • hours = int(input("How many hours did you work? "))
    • How it works: The input() call returns a string, which is immediately passed to int() to produce an integer, which is then assigned to hours.
  • Pay rate example (float conversion): read hourly pay rate and convert to float
    • pay_rate = float(input("What is your hourly pay rate? "))
  • Comprehensive example (string, int, and float in one program): Program 2.13 reads a string, an int, and a float
    • One possible structure:
    • name = input("What is your name? ")
    • age = int(input("What is your age? "))
    • income = float(input("What is your income? "))
    • Program output (example):
    • Here is the data you entered
    • Name: Chris
    • Age: 25
    • Income: 75000.0
    • The transcript shows a slightly different formatting in the printing, but the essential idea is the same: display the entered values after conversion.

How conversion works in practice and potential errors

  • The conversion functions only work if the input contains a valid numeric value:
    • If the argument cannot be converted, an exception occurs. In Python, this is typically a ValueError.
  • Example of an exception during conversion:
    • Interactive session: entering a non-numeric value where int is expected causes an error such as:
    • ValueError: invalid literal for int with base 10
  • End user concept: the user or end user is the person providing input to the program.

Nested function calls vs multiple statements (efficiency and clarity)

  • Two-statement approach:
    • string_value = input("Enter something: ")
    • value = int(string_value)
  • Single-statement approach (preferred for straightforward conversions):
    • value = int(input("Enter something: "))
  • Conceptual flow: The input() function obtains a string, which is then passed as the argument to the conversion function (int or float), and the result is stored in the target variable: target=int(input())\text{target} = \text{int}(\text{input}(\dots)) or target=float(input())\text{target} = \text{float}(\text{input}(\dots))

Additional examples to reinforce concepts

  • Reading a user’s name (string) and a numeric value (int) and a numeric value (float):
    • name = input("What is your name? ")
    • age = int(input("What is your age? "))
    • salary = float(input("What is your salary? "))
  • Displaying the entered values:
    • print("Here is the data you entered:")
    • print("Name:", name)
    • print("Age:", age)
    • print("Salary:", salary)

Practical implications and considerations

  • Input returns text; non-numeric input will fail conversion to int/float and must be handled (try/except) in robust programs, though error handling is not covered in this section.
  • When prompting for input, consider user experience: include spaces after prompts for readability.
  • Be explicit about expected input types to minimize errors (e.g., specify units or formats in the prompt).
  • Real-world relevance: many programs require numeric input for calculations, pricing, quantities, etc.; knowing how to safely convert input is essential.
  • Foundational principles connected to input/output in programming: capturing user input, type conversion, and basic error handling patterns.

End-user and equitable design considerations (brief)

  • The material touches on the end-user concept (the user providing input). In real-world design, consider clarity, accessibility, and error handling to improve user experience and reduce input errors.

Checkpoint-style prompts (from the book)

  • 2.17: You need the user of the program to enter a customer's last name. Write a statement that prompts the user to enter this data and assigns the input to a variable.
    • Example answer: last_name = input("Enter customer's last name: ")
  • 2.18: You need the user of the program to enter the amount of sales for the week. Write a statement that prompts the user to enter this data and assigns the input to a variable.
    • Example answer: sales = float(input("Enter the total sales for the week: "))

Notes and caveats:

  • The examples assume Python-like syntax consistent with the chapter material.
  • If you expect numeric input, consider validating or handling exceptions to avoid program crashes due to invalid input.
  • The embedded equation-style representations are included to emphasize the data flow: input -> string, then optional conversion to int/float for arithmetic operations.