繁体   English   中英

输入范围无效后如何重新提示循环用户输入

[英]How to re-prompt loop user input after invalid input range

房间数量的用户输入范围是 [1-8]。 此处的无效输入应显示'无效输入'并一直重新提示,直到收到有效输入以执行程序 rest。 我已经将服务返回和“无效服务”的输入设置为无效,输入房间数也应如此。

def main():
    small = 60
    medium = 120
    large = 145
    servOne = 40
    servTwo = 80


    numRooms = int(input("Number of rooms in the house?: "))

    while True:
        restart = int(input("Sorry Invalid number of rooms,try again? "))
        if int(numRooms) < 1 or int(numRooms) > 8 in restart:
            continue
            (???)

       




    servType = input("Type of cleaning service requested? (carpet cleaning or window cleaning): ")


    if int(numRooms) <= 2:
        print("Calculating fees for small house...")

        if servType == "carpet cleaning":
            print("Total cost of service:$",(small+servOne))

        elif servType == "window cleaning":
            print("Total cost of service:$",(small+servTwo))

        else:
            print("Sorry! Invalid service input")



    if int(numRooms) >= 3 and int(numRooms) <= 5:
        print("Calculating fees for medium house...")

        if servType == "carpet cleaning":
            print("Total cost of service:$",(medium+servOne))

        elif servType == "window cleaning":
            print("Total cost of service:$",(medium+servTwo))

        else:
            print("Sorry! Invalid service input")



    if int(numRooms) >= 6:
        print("Calculating fees for large house...")

        if servType == "carpet cleaning":
            print("Total cost of service:$",(large+servOne))

        elif servType == "window cleaning":
            print("Total cost of service:$",(large+servTwo))

        else:
            print("Sorry! Invalid service input")

主要的()

只需将输入包装在一个 while 循环中。 如果收到有效输入,则结束循环

valid_input=False 
while not valid_input:
    i=input("Number of rooms in the house?:")
    inp=int(i)
    if inp in range(1,9):  #(9 is not included)
        valid_input=True 
. 
.
remaining code 
.
.

上面的另一种写法..更容易理解

while  1==1:  # repeat loop(all statements below) forever
    i=input("Number of rooms in the house?:")
    inp=int(i)
    if inp in range(1,9):  #(9 is not included)
        break # break out of the forever loop
#end of loop

一种选择(如果我假设你正在尝试做什么)是使用递归 function 而不是 while 循环,并在无效输入时再次调用 function :


def Main():
  validnums = [1,2,3]
  i = Input("Please Enter input")
  if int(i) not in validnums:
    Main()
  else:
    ##Do stuff
  Main()

通过让 Main() 调用 Main(),它的功能与 while 循环相同,但您可以随时重新启动它。 我希望这有帮助。

如果你想避免递归:

def Main():
  validnums = [1,2,3]
  While True:
    i = input()
    if int(i) not in validnums:
     break
  Main()

这使用了一个 while 循环,而 function 仅在需要时调用自身。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM