防止 Python 中用户的空输入
为了防止空的用户输入:
- 使用 while 循环进行迭代,直到用户输入非空字符串。
- 在每次迭代中,检查用户是否没有输入空字符串。
- 如果满足条件,则退出 while 循环。
country = ''
# ✅ 防止空输入
while country == '':
country = input('Where are you from: ')
print(country)
# ---------------------------------------------
# ✅ 防止空输入 (including whitespace characters)
while country.strip() == '':
country = input('Where are you from: ')
print(country)
第一个示例在用户输入空字符串时不断提示。
第二个示例还将空白字符视为空输入。
我们使用 while 循环进行迭代,直到 country 变量不存储空字符串。
country = ''
while country == '':
country = input('Where are you from: ')
如果用户输入的值至少包含 1 个字符,则不再满足条件并退出 while 循环。
输入函数接受一个可选的提示参数并将其写入标准输出,而没有尾随的换行符。
然后该函数从输入中读取该行,将其转换为字符串并返回结果。
如果想阻止用户只输入空格,请使用 str.strip()
方法。
country = ''
while country.strip() == '':
country = input('Where are you from: ')
str.strip
方法返回删除了前导和尾随空格的字符串副本。
print(repr(' '.strip())) # 👉️ ''
print(repr(' hello '.strip())) # 👉️ 'hello'
while 循环一直运行,直到用户输入至少一个非空白字符。
或者,我们可以使用 while True
循环。
while True:
country = input('Where are you from: ')
if country.strip() != '':
print(country)
break
在每次迭代中,我们检查用户是否输入了至少一个字符。
如果条件满足,我们使用 break
语句退出循环。
break
语句跳出最里面的 for
或 while
循环。
确保使用 break
语句,因为它是退出 while True
循环的唯一方法。
相关阅读:
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。