SoFunction
Updated on 2025-04-14

Detailed explanation of input and output formatting operations in Python

introduction

In Python programming, input and output are the core parts of the program's interaction with users. The output formatting is a great enhancement to the program's expression ability, allowing the results to be presented to users in a clear, beautiful and easy to read manner. This article will explore in-depth Python input and output operations, especially how to use formatting methods to improve code quality and readability.

1. Input operation

Python provides simple and powerful input functions through built-in functionsinput()You can get input in string form from the user. Here are some basic usages and precautions:

1. Basic usage

name = input("Please enter your name: ")
print(f"Hello, {name}!")

2. Convert data types

input()The returned value is always of string type. If integers, floating point numbers, or other types are required, explicit conversion must be:

age = int(input("Please enter your age: "))
height = float(input("Please enter your height(rice): "))
print(f"You're this year {age} age,height {height:.2f} rice。")

3. Handle exception input

Incorrect input may often occur when users enter data. Therefore, we can usetry...exceptTo catch exceptions:

try:
    age = int(input("Please enter your age: "))
    print(f"Your age is {age}")
except ValueError:
    print("The input is not a valid integer!")

4. Notes on type conversion

For complex input scenarios, strings can be parsed into lists, dictionaries, or other types. For example:

# Convert comma separated strings to listnumbers = input("Please enter a set of numbers, separated by commas: ").split(",")
numbers = [int(num) for num in numbers]
print(f"The number you entered is: {numbers}")

# Convert JSON format string to dictionaryimport json
data = input("Please enter data in JSON format: ")
data_dict = (data)
print(f"The parsed data: {data_dict}")

2. Output operation

Python provides a variety of methods for output, the most commonly used one isprint()Function. The following details the formatting method of the output.

1. Basic output

print()Functions can directly output strings, variables, expressions, etc.:

x = 10
y = 20
print("x + y =", x + y)

2. Format output method

Format output is a very powerful feature in Python and can be implemented in a variety of ways.

2.1 Using old style % format

This is an earlier formatting method in Python, similar to the C languageprintf

name = "Alice"
age = 25
print("The age of %s is %d." % (name, age))
  • Common formats:
    • %s: String
    • %d: integer
    • %f: Floating point number
    • %.2f: Keep two decimal places to float

2.2 Using  ()

This method is more flexible and supports inserting variables by position or by name:

# By locationprint("{0} The age is {1} age。".format(name, age))

# By nameprint("{name} The age is {age} age。".format(name="Bob", age=30))

# Format floating point numberspi = 3.14159
print("Pi is {0:.2f}".format(pi))

2.3 Using f-string (recommended)

Starting with Python 3.6, f-string provides a simpler and more intuitive formatting method:

name = "Charlie"
age = 28
print(f"{name} The age is {age} age。")

# Support expressionsx = 5
y = 3
print(f"{x} + {y} = {x + y}")

# Floating point number formattingprint(f"Pi is {pi:.2f}")

3. Multi-line output

Use a three-quoted string ('''or""") Multi-line output can be easily implemented:

print("""This is the multi-line output:
 First line
 Line 2
 The third line
 """)

4. Control characters and escape characters

  • Line breaks:\n
  • Tab characters:\t
  • Backslash:\\
print("Python\nProgramming\tLanguage")

III. Comprehensive case

Here is a case combining input, output and formatting:

Case description

Write a simple shopping settlement program where the user enters the product name, unit price and quantity, the program calculates the total price and outputs a formatted bill.

Implement code

print("Welcome to use the shopping checkout program")

try:
    product = input("Please enter the product name: ")
    price = float(input("Please enter the unit price of the product: "))
    quantity = int(input("Please enter the purchase quantity: "))

    total = price * quantity

    print("\nClosing bill:")
    print(f"Product Name: {product}")
    print(f"Product unit price: {price:.2f} Yuan")
    print(f"Purchase quantity: {quantity}")
    print(f"Total price: {total:.2f} Yuan")

except ValueError:
    print("The input data format is incorrect, please try again!")

Running example

Welcome to the shopping checkout program
Please enter the product name: Apple
Please enter the unit price of the product: 3.5
Please enter the purchase quantity: 4

Settlement bills:
Product Name: Apple
Unit price of the product: 3.50 yuan
Purchase quantity: 4
Total price: 14.00 yuan

4. Summary

Through in-depth understanding and practice of input and output, Python programmers can better interact with users and present results in an elegant way. Whether it is simpleprint(), or complex formatted output, mastering these techniques is crucial to writing high-quality code. In actual development, choosing the appropriate formatting method according to specific needs can greatly improve the readability and user experience of the program.

This is the introduction to this article about the detailed explanation of input and output formatting operations in Python. For more related Python input and output formatting content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!