Master Python Input & Output: From Basics to Practical Tricks
This tutorial explains why input and output are essential in Python, demonstrates how to use the input function with handling of empty strings, type conversion, whitespace stripping, validation, and how to leverage print for simple and formatted output, including % formatting and custom separators.
Why Input and Output Matter
From the classic "hello world" to more complex examples, a program becomes meaningful only when it can receive user input, process it, and display results on the screen.
Input Function
The input() function always returns a string, even if the user types a number. Simple examples illustrate this behavior:
# Example 1
inp = input("please input your name: ")
# User types: jack
print(inp) # 'jack'
print(type(inp)) # <class 'str'>
# Example 2
age = input("please input your age: ")
print(age) # '18'
print(type(age)) # <class 'str'>
# Example 3 (empty input)
empty = input("Enter something: ")
print(empty) # ''
# Example 4 (preserve whitespace)
a = input("请输入一个字符:")
print(a) # ' 前后带有空白 'Common handling patterns include:
# Prompt again if input is empty
inp = input("请输入你的姓名: ")
if inp == "":
inp = input("姓名不能为空,请重新输入: ") # Convert string to integer safely
age = input("请输入你的年龄:")
if age.isdigit():
age = int(age)
print("你的年龄是:", age)
else:
print("输入不合法!") # Strip whitespace
inp = input("请输入你的姓名: ")
inp = inp.strip()
print(inp)Input can also be used to pause program execution:
print("程序前面部分执行完毕......")
input("请按回车继续......") # waits for Enter
print("继续执行程序的后面部分......")Print Function
The print() function sends formatted text to standard output. It accepts multiple arguments separated by commas, automatically inserting spaces.
a = "i am"
b = "student"
print(a, "a", b) # i am a student
print(a+"a"+b) # i ama studentKey parameters:
sep : separator between arguments (default space).
end : string appended after the last value (default newline). Setting end='' prevents a line break.
print(a, "a", b, sep="*") # i am*a*studentFormatted Output with % Operator
Python supports C‑style % formatting. Place format specifiers like %s or %d in a string and provide a tuple of values.
print("我叫 %s 今年 %d 岁!" % ("小明", 10))Examples of various specifiers and mappings:
s = "i am %s" % "jack"
print(s)
s = "i am %s age %d" % ("jack", 18)
print(s)
s = "i am %(name)s age %(age)d" % {"name": "jack", "age": 18}
print(s)
s = "percent %.2f" % 99.97623
print(s)
s = "i am %(pp).2f" % {"pp": 123.425556}
print(s)
s = "i am %.2f %%" % 123.425556
print(s)To print a literal percent sign, use %%.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
