如何重做“if”语句?

2024-09-30 05:15:18 发布

您现在位置:Python中文网/ 问答频道 /正文

如果用户犯了错误或输入了错误的内容,我试图让用户通过if语句返回。我可以让他/她重新启动循环,但不只是将一个循环移回,如何将一个循环移回break杀死循环,我需要它返回

def storepurchasing():
    typeofdevice = input("Enter the tye of item you want as the number indicated as an index \n 1: Phone \n 2: Tablet \n\n Your selection: ")

    while True:
         if typeofdevice == "1":
             break
             while True:
                  typeofphone = input("Enter phone you want you want as the number indicated as an index \n 1: BPCM \n 2: BPSH \n 3: RPSS \n 4: RPLL \n 5: YPLS \n 6: YPLL\n\n Your selection: ")
                  if typeofphone == "1":
                     pass
                  elif typeofphone == "2":
                     pass
                  elif typeofphone == "3":
                     pass
                  elif typeofphone == "4":
                     pass
                  elif typeofphone == "5":
                     pass
                  elif typeofphone == "6":
                     pass
                  elif typeofdevice == "2":
                     pass
             else:
                print("please enter a valid input between 1 and 2")

Tags: the用户younumberinputifas错误
2条回答

在您的情况下,使用continue比使用break更好地在输入无效的情况下重新启动循环

def storepurchasing():
    while True:                                                  ## loop 1
        typeofdevice = input("Enter the tye of item you want as the number indicated as an index \n 1: Phone \n 2: Tablet \n\n Your selection: ")
        if typeofdevice not in [str(n) for n in range(1,3)]:
            print("please enter a valid input between 1 and 2 \n")
            continue                                             ## restart loop 1 in typeofdevice is not in ['1', '2']

        if typeofdevice == "1":
            while True:                                          ## loop 2
                typeofphone=input("Enter phone you want you want as the number indicated as an index \n 1: BPCM \n 2: BPSH \n 3: RPSS \n 4: RPLL \n 5: YPLS \n 6: YPLL\n\n Your selection: ")
                if typeofphone not in [str(n) for n in range(1,7)]:
                    print("please enter a valid input between 1 and 6 \n")
                    continue                                     ## restart loop 2 in typeofphone is not in ['1', '2', '3', '4', '5', '6']

                if typeofphone == "1":
                    ## do something
                elif typeofphone == "2":
                    ## do something
                .......

        elif typeofdevice == "2":
            ## do something

应该用break语句替换那些pass语句。您还可以将所有这些条件检查放在一行中:

while True:
    typeofphone=input('...')
    if typeofphone in [str(n) for n in range(1,7)]:
        break
    print('Please enter a valid input between 1 and 6')

相关问题 更多 >

    热门问题