小白编程
亮色模式 暗色模式 跟随系统
首页 Python

如何在 Python 中使用 input() 函数获取用户输入

发布日期:

在本文中,你将学习如何使用 input() 函数来获取用户输入,并处理这些输入以创建交互式程序。无论是需要一个名字还是一个名单,input() 都能帮助你实现目标。

input() 函数的工作原理

input() 函数让程序暂停运行,等待用户输入一些文本。一旦用户完成输入并按下回车键,Python 将用户的输入赋值给一个变量,以便后续使用。

例如,下面的程序让用户输入一些文本,然后将其回显:

1
2
message = input("Tell me something, and I will repeat it back to you: ")
print(message)

在这个例子中,当程序运行时,用户会看到提示:“Tell me something, and I will repeat it back to you:”。用户输入后按回车键,输入的内容被赋值给变量 message 并打印出来。

编写清晰的提示

每当使用 input() 函数时,都应该提供一个清晰易懂的提示,告诉用户应该输入什么信息。这有助于提高用户体验和程序的可读性。

例如:

1
2
name = input("Please enter your name: ")
print(f"\nHello, {name}!")

为了使提示更加直观,可以在提示末尾(通常是冒号后面)添加一个空格,这样用户就能清楚地知道输入从何处开始:

1
2
Please enter your name: Eric
Hello, Eric!

如果提示较长或需要解释获取特定输入的原因,可以先将提示赋值给一个变量,再传递给 input() 函数。这使得代码更加清晰:

1
2
3
prompt = "If you share your name, we can personalize the messages you see.\nWhat is your first name? "
name = input(prompt)
print(f"\nHello, {name}!")

这样做的好处是即使提示超过一行,代码依然简洁明了:

1
2
3
If you share your name, we can personalize the messages you see.
What is your first name? Eric
Hello, Eric!

使用 int() 获取数值输入

默认情况下,input() 返回的是字符串。如果你需要进行数值比较或计算,必须使用 int() 将输入转换为整数。否则,尝试对字符串执行数值操作会导致错误。

例如:

1
2
3
4
5
6
7
age = input("How old are you? ")
age = int(age)

if age >= 18:
    print("\nYou are an adult.")
else:
    print("\nYou are a minor.")

在这个例子中,用户输入年龄后,int() 函数将输入的字符串转换为整数,从而使条件判断能够正常工作。

求模运算符

求模运算符 % 是一种有用的工具,它用于返回两个数相除后的余数。这对于判断一个数是否能被另一个数整除非常有用。

例如:

1
2
3
4
4 % 3  # 结果是 1
5 % 3  # 结果是 2
6 % 3  # 结果是 0
7 % 3  # 结果是 1

利用求模运算符,我们可以编写一个简单的程序来判断一个数是奇数还是偶数:

1
2
3
4
5
6
7
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)

if number % 2 == 0:
    print(f"\nThe number {number} is even.")
else:
    print(f"\nThe number {number} is odd.")

如果一个数能被 2 整除(即 number % 2 == 0),那么这个数就是偶数;否则,它是奇数。

相关文章