title: python input and output description: Use the print() function to output content to the screen:

Python input and output (IO) brief tutorial

When you are new to programming, the first thing you need to understand is "talking to the program" - let the program output things according to your ideas, and then let it understand what you say. Python is designed to be very friendly in this regard, with no complicated syntax threshold.


1. Output Output: Print out the "words" of the program

There is only one core output tool in Python:print()Functions are easy to use.

1.1 Basic single value output

Whether it is a string, a number, a Boolean value, or a simple calculation expression, just put it in parentheses:

# 输出字符串,记得加引号!
print('hello, python')
print("单双引号都可以哦")

# 输出整数、浮点数
print(2024)
print(13.14)

# 输出计算结果,程序会先算完再打印
print(1024 * 768)

1.2 Multi-parameter batch output

If you want to print several contents at the same time, you don’t need to concatenate the strings, just separate the parameters with commas - Python will add space in the middle and newline at the end by default:

print('The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog')
# 输出结果:The quick brown fox jumps over the lazy dog

1.3 Elegant formatted output f-string

Although it is convenient to use commas for batch printing, to "embed" variables or calculation results into a complete paragraph, f-string (formatted string literal) is the most recommended way of writing in Python 3.6+ - the syntax is intuitive and the code is easy to read:

width = 1024
height = 768
# 在字符串前加 f/F,用 {} 包裹变量/表达式
print(f"屏幕分辨率是:{width} × {height},总像素为 {width * height}")

2. Input: Let the program "listen" to you

Python has only one core input tool:input()function, it will pause the program and wait for you to enter the Enter key in the terminal before continuing execution.

2.1 Basic silent input

Without any parameters, the program will directly wait for your input without any prompts on the terminal:

# 先运行程序,然后打字,按回车结束
name = input() 
print(name)

2.2 Input with friendly prompts

It is best to add a prompt to the user to avoid not knowing what to enter - just insert the prompt textinput()Just parentheses:

name = input("请输入你的昵称:")
print(f"欢迎来到 Python 世界,{name}👋")

2.3 Input type conversion (important and error-prone points)

⚠️ Note: No matter you enter numbers, letters or symbols,input()Always return string type! If you want to use it for mathematical operations, you must manually convert it intoint(integer) orfloat(floating point number):

# 先输入提示,再转类型
age = int(input("请输入你的年龄:"))
next_year_age = age + 1
print(f"明年你就 {next_year_age} 岁啦!")

height = float(input("请输入你的身高(米):"))
print(f"你的身高是 {height}m")

Core Rules:input()What you get is alwaysstr, you must first change the type if you want it to count, otherwise there will be problems that give you a headacheTypeError


3. Quick preparation: variable basics

To store the input or calculation results for repeated use, you have to use variables - it is like a named "storage box" that can store various types of data:

# 整数
year = 2024
# 浮点数
pi = 3.14159
# 字符串(单/双引号都可,三引号可以存多行)
address = '北京市朝阳区'
# 布尔值(只有 True/False 两个值,注意首字母大写)
is_student = True

4. Comprehensive example: simple addition, subtraction, multiplication and division calculator

Combine the output, input, variables, and type conversions you just learned, and write a usable gadget to practice:

# 1. 获取用户输入的两个数字并转类型
num1 = float(input("请输入第一个数字:"))
num2 = float(input("请输入第二个数字:"))

# 2. 做计算并打印格式化结果
print("-" * 20)  # 打印分隔线
print(f"{num1} + {num2} = {num1 + num2}")
print(f"{num1} - {num2} = {num1 - num2}")
print(f"{num1} × {num2} = {num1 * num2}")  # Python 3 中 × 可以直接显示,但习惯用 * 更通用
print(f"{num1} ÷ {num2} = {num1 / num2}")

5. Modern Python IO tips

  1. Prefer using f-string instead of the old one%Format orstr.format(), the code is more concise.
  2. Add basic input verification (such as determining whether the input is a number), otherwise the program will easily crash due to incorrect input.
  3. Try type annotations (Python 3.5+). Although it does not affect the operation, it will make it clearer for yourself and others to read the code:
    def greet_user() -> None:
        """向用户问好的简单函数"""
        name: str = input("请输入你的名字:")
        print(f"你好,{name}!")
    
    if __name__ == '__main__':
        greet_user()
  4. If you need more cool terminal interaction (such as colored text, progress bar), you can use a third-party libraryrichorclick

Summarize

  • print(): Output any content, support single/multiple parameters, f-string
  • input(): Get user input, always return a string, remember to do type conversion
  • ✅ Variable: "Box with name" to store data
  • ✅ Best practices: use f-string more, add hints, and add type annotations