在 Python 中使用用户输入进行 while 循环
在 while 循环中获取用户输入:
-
使用
while
循环进行迭代,直到满足条件。 -
使用
input()
函数获取用户输入。 -
如果满足条件,则退出
while
循环。
# 👇️ 带有用户输入字符串的while循环
password = ''
while True:
password = input('Enter your password: ')
if len(password) < 4:
print('Password too short')
continue
else:
print(f'You entered {password}')
break
print(password)
# ----------------------------------------
# 👇️ 带有用户输入数字的while循环
num = 0
while True:
try:
num = int(input("Enter an integer 1-5: "))
except ValueError:
print("Please enter a valid integer 1-5")
continue
if num >= 1 and num <= 5:
print(f'You entered: {num}')
break
else:
print('The integer must be in the range 1-5')
第一个示例使用 while
循环进行迭代,直到提供的值的长度至少为 4 个字符。
如果值太短,我们使用 continue
语句继续下一次迭代。
password = ''
while True:
password = input('Enter your password: ')
if len(password) < 4:
print('Password too short')
continue
else:
print(f'You entered {password}')
break
print(password)
如果该值至少有 4 个字符长,我们使用 break 语句作为输入有效。
continue
语句继续循环的下一次迭代。
break
语句跳出最里面的 for 或 while 循环。
在
while
循环中验证用户输入时,我们在输入无效时使用continue
语句,例如 在 except 块或 if 语句中。
如果输入有效,我们使用 break 语句退出 while 循环。
我们可以在验证数字输入时使用相同的方法。
num = 0
while True:
try:
num = int(input("Enter an integer 1-5: "))
except ValueError:
print("Please enter a valid integer 1-5")
continue
if num >= 1 and num <= 5:
print(f'You entered: {num}')
break
else:
print('The integer must be in the range 1-5')
我们使用 while
循环进行迭代,直到提供的输入值在指定范围内。
如果 try
块成功完成,则用户输入一个整数。
if
语句检查整数是否在 1-5 范围内,如果满足条件,我们就跳出while
循环。
如果整数不在指定范围内,则 else
块运行并打印一条消息。
如果用户没有输入整数,则运行 except
块,我们使用 continue
语句再次提示用户。
相关文章
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 日期时间。