You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Python while循环中重复输出问题?附代码示例

问题解决:while循环重复输出输入提示的问题

问题原因

你的代码在while循环体内连续调用了两次selection()函数,而selection()函数内部应该包含了输入提示逻辑(比如input("Please enter a number: ")),每次调用该函数都会触发一次输入提示,因此才会出现两次"Please enter a number"的输出。

解决方案

将selection()的调用结果存储到一个变量中,后续的判断逻辑都基于这个变量,这样就只会调用一次selection(),也就只会触发一次输入提示。同时推荐将多个独立的if语句改为elif,避免多条件误触发,并补充选项3的退出逻辑,让程序更完整。

修改后的代码

def login():
    print("Welcome to David's and John's Tenant Management System!")
    print("(1)Admin (2)Customer (3)Exit")
    while True:
        user_choice = selection()  # 仅调用一次selection(),保存结果到变量
        if user_choice == "1":
            print("f")  # admin login
        elif user_choice == "2":
            print("Are you an existing user? Enter 1 if YES, 2 for NO.")
            break
        elif user_choice == "3":
            print("Exiting the system...")
            break
login()

补充selection()函数示例

确保selection()函数的基础实现正确,示例如下:

def selection():
    return input("Please enter a number: ")

内容的提问来源于stack exchange,提问作者Monchi Yui

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 16:27:25