User Interaction in Programming Basics

Oct 7, 2024

Programming with User Interaction

Introduction

  • Learn to create programs that respond to user inputs.
  • The individual running the program is referred to as the "user."
  • Previously, programs interacted in a one-way fashion (output only).

Two-Way Interaction

  • New goal: Write programs that ask the user for information.
  • Need to retrieve and store user input.
  • Variables can store input.

Using the input() Function

  • Retrieves text from the user.
  • To use, include a string prompt in parentheses.
  • Execution pauses until the user inputs and presses Enter.
  • Example:
    name = input("Enter your name: ")
    print(name)
    
  • Type of input: Stored as str (string).
  • Any user entry, even numbers, is initially a string.

Converting Strings to Numbers

  • Problem: Cannot perform arithmetic on a string.
  • Solution: Use int() to convert a string to an integer.
  • Example:
    • User enters a number, stored initially as string.
    • int() converts it for arithmetic operations.

Function Composition

  • Evaluate expressions from the inside out.
  • Example process:
    1. input() captures user input.
    2. int() converts input string to integer.
    3. Store integer in a variable.
  • Concept helps manage complex expressions in programming.

Conclusion

  • Understanding user input and data conversion is essential.
  • Mastery of these concepts is foundational for interactive programming.