返回
在 Python 中如何处理用户输入 “no” 并重新启动程序?
python
2024-03-20 14:32:09
用 Python 应对用户输入 “no” 时重新启动程序
在 Python 编程中,如果你希望在用户输入 “no” 时重新启动程序而不是结束它,可以使用 while 循环和条件语句实现此功能。
问题
假设你有以下代码:
while True:
# 获取用户输入
product = input("Enter product name: ")
price = float(input("What is the price of the product: "))
# 打印用户信息
print(f'''You want to save towards purchasing {product.title()} which costs {price} dollars(Can)''')
# 询问用户是否正确
correct = input ("Is this correct, Yes or No: ")
# 处理用户输入
if correct == "no":
print("Re-enter correct data")
if correct == "yes":
break
当用户输入 “no” 时,此代码会打印 “Re-enter correct data”,但程序会继续运行。你想让用户能够重新输入产品名称和价格,而不是结束程序。
解决方案
要解决此问题,你可以使用以下修改后的代码:
while True:
# 获取用户输入
product = input("Enter product name: ")
price = float(input("What is the price of the product: "))
# 打印用户信息
print(f'''You want to save towards purchasing {product.title()} which costs {price} dollars(Can)''')
# 询问用户是否正确
correct = input ("Is this correct, Yes or No: ")
# 处理用户输入
if correct == "no":
continue # Restart the loop
if correct == "yes":
break # Exit the loop
这段修改后的代码使用 continue 语句在用户输入 “no” 时重新启动循环。这意味着程序将返回循环的开始并再次提示用户输入产品名称和价格。
当用户输入 “yes” 时,程序将使用 break 语句退出循环并继续执行程序的其余部分。
实际应用
while True:
# 获取用户输入
product = input("Enter product name: ")
price = float(input("What is the price of the product: "))
# 打印用户信息
print(f'''You want to save towards purchasing {product.title()} which costs {price} dollars(Can)''')
# 询问用户是否正确
correct = input ("Is this correct, Yes or No: ")
# 处理用户输入
if correct == "no":
continue # Restart the loop
if correct == "yes":
break # Exit the loop
# 添加其他代码来计算节省的费用等
通过使用 continue 和 break 语句,你可以轻松地在用户输入 “no” 时重新启动你的 Python 程序。这使得你的程序对用户交互更加灵活和友好。
常见问题解答
1. 为什么使用 while 循环?
while 循环允许你不断提示用户输入,直到他们输入正确的信息或选择退出。
2. continue 语句有什么作用?
continue 语句用于在循环的当前迭代中重新启动循环,从而跳过循环中的剩余代码。
3. break 语句有什么作用?
break 语句用于退出循环并继续执行程序的其余部分。
4. 我如何自定义重新启动时的提示消息?
你可以通过修改 print("Re-enter correct data") 语句来自定义重新启动时的提示消息。
5. 我可以在循环中使用其他条件吗?
是的,你可以根据需要在循环中使用其他条件。例如,你可以检查用户是否输入了空字符串或无效字符。