1.2 Input/output

2 min readjune 24, 2024

and functions are essential for interacting with users and managing data flow in Python programs. These functions allow you to display information, collect user input, and convert data types for calculations.

Understanding how to use print() and effectively is crucial for creating interactive programs. You'll learn to customize output, handle user input, and convert data types to perform operations, laying the foundation for more complex programming tasks.

Input and Output Functions

Custom output with print()

  • print()
    displays output to the console ()
  • Separates arguments with a space by default and ends with a newline character
  • Customize the separator using the
    [sep](https://www.fiveableKeyTerm:sep)
    parameter
    • print("Hello", "world", sep="-")
      outputs "Hello-world"
  • Customize the line ending using the
    [end](https://www.fiveableKeyTerm:end)
    parameter
    • print("Hello", end="")
      outputs "Hello" without a newline
    • print("Hello", end=" ")
      outputs "Hello " with a space instead of a newline
  • Use to include special characters
    • [\n](https://www.fiveableKeyTerm:\n)
      for newline,
      [\t](https://www.fiveableKeyTerm:\t)
      for tab
    • print("Hello\nworld")
      outputs "Hello" on one line and "world" on the next

User input and variable storage

  • input()
    gets input from the user via the console ()
  • Prompts the user to enter a value and waits for input
  • Returns the user's input as a string
  • Assign the result of
    input()
    to a variable to store the user's input
    • name = input("Enter your name: ")
      prompts the user and stores the input in
      name
  • Provide a message as an argument to guide the user
    • Displayed before the user enters their input
    • age = input("Enter your age: ")
      prompts with "Enter your age: "

Data type conversion for calculations

  • User input is always returned as a string by
    input()
  • Convert the input to the appropriate data type for numerical operations
    • [int](https://www.fiveableKeyTerm:int)()
      converts input to an integer
      • num = int(input("Enter a number: "))
        converts input to integer and stores in
        num
    • [float](https://www.fiveableKeyTerm:Float)()
      converts input to a floating-point number
      • price = float(input("Enter the price: "))
        converts input to float and stores in
        price
  • Attempting numerical operations on strings will result in a
    [TypeError](https://www.fiveableKeyTerm:TypeError)
    • result = "10" + 5
      raises an error (cannot add string and integer)
  • Handle invalid input by catching exceptions with a
    try-except
    block
    • Catch
      [ValueError](https://www.fiveableKeyTerm:ValueError)
      exceptions when converting input to numerical data types
    • Example:
      try:
          age = int(input("Enter your age: "))
      except ValueError:
          print("Invalid input. Please enter a valid integer.")
      

Advanced I/O Operations

  • allows reading from and writing to files on the system
  • can improve performance by reducing the number of I/O operations
  • options enable precise control over output appearance

Key Terms to Review (24)

\n: The newline character, denoted as '\n', is a special character in programming that represents the end of a line of text and the start of a new line. It is a fundamental concept in input/output operations, string basics, and string manipulation in Python.
\t: \t is a special character in programming languages, including Python, that represents a horizontal tab. It is used to insert a tab space, which can be useful for aligning text or creating formatted output.
Buffering: Buffering is a technique used in computer systems to temporarily store data in a buffer, which is a reserved area of memory, before it is processed or transmitted. This helps manage the flow of data and ensures that information is not lost or corrupted during input/output operations or file reading/writing processes.
End: The term 'end' in the context of input/output refers to the completion or termination of an input or output operation. It signifies the point at which the process of receiving or transmitting data concludes.
Escape Characters: Escape characters are special characters used in programming to represent certain actions or non-printable characters. They are denoted by a backslash (\) followed by a specific character and are used to create special formatting or control the behavior of a string.
File I/O: File I/O, or file input/output, refers to the process of reading from and writing to files on a computer's storage system. It allows programs to interact with and manipulate data stored in files, enabling the storage and retrieval of information beyond the runtime of the program.
Float: A float is a data type in programming that represents a decimal number, allowing for the storage of numbers with a fractional component. Floats are used to handle numerical values that require precision beyond what can be represented by integers.
Float()-function: The float() function in Python is used to convert a value into a floating-point number, which is a data type that can represent decimal values. This function is particularly useful in the context of input/output operations, where user input or data from external sources may need to be converted to a numerical format for further processing.
Formatting: Formatting refers to the way data is presented and structured within a computer program or document. It involves the arrangement, layout, and visual presentation of information to enhance readability, organization, and overall user experience.
Input: Input in Python is data provided by the user to the program, typically through the keyboard. It can be captured using the input() function and stored in variables for further processing.
Input(): The input() function in Python is used to receive data from the user during the execution of a program. It allows the program to pause and wait for the user to enter some information, which is then stored in a variable for further processing.
Input()-function: The input()-function in Python is a built-in function that allows the user to provide data input during the execution of a program. It pauses the program's execution and waits for the user to enter a value, which is then assigned to a variable for further processing.
Int: The 'int' data type in Python represents whole numbers or integers, which are numbers without fractional parts. It is a fundamental data type that is used extensively in programming to store and manipulate numeric values.
Int()-function: The int() function in Python is used to convert a value into an integer data type. It is a built-in function that takes a single argument and returns an integer representation of that value.
Output: Output refers to the information or data that is produced or generated by a computer program or system. It is the result of processing input data and represents the final outcome or product of a computational process.
Print()-function: The print()-function is a built-in Python function used to output data to the console. This function plays a crucial role in displaying results, debugging code, and providing feedback to users. By allowing the programmer to output various data types, such as strings, numbers, and variables, it becomes an essential tool for interacting with the program's environment.
Prompt: A prompt is a message displayed to the user to request input. In Python, it is commonly used with the input() function.
Sep: The 'sep' parameter in Python's print() function is used to specify the separator character(s) that will be placed between the values being printed. It determines how the individual elements are separated from each other in the output.
Stdin: stdin, or standard input, is a concept in computer programming that refers to the default source of input data for a program. It allows users to interact with a program by providing input through the keyboard or other input devices.
Stdout: stdout, or standard output, is a stream in computer programming that represents the default output destination for a program's data. It is a fundamental concept in input/output (I/O) operations, allowing programs to communicate their results or any other information to the user or to other programs.
Str: The str (string) data type in Python is a collection of one or more characters that can include letters, digits, and various symbols. Strings are used to represent and manipulate textual data within a Python program.
Type Casting: Type casting is the process of converting a value from one data type to another. It allows programmers to change the way data is represented and interpreted within a program, enabling them to perform operations and comparisons between different data types.
TypeError: A TypeError is an exception that occurs when an operation or function is performed on a value of an inappropriate type. It indicates that the operands of an operation are not compatible with the operation or that a function is called with arguments of the wrong type.
ValueError: ValueError is an exception that is raised when a function receives an argument of the correct type but an inappropriate value. This can occur in various contexts, such as when converting data types, handling user input, or working with mathematical operations.
© 2024 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.
Glossary
Glossary