【问题标题】:Nested while loop - Python嵌套的while循环 - Python
【发布时间】:2014-06-18 03:40:11
【问题描述】:

我正在开发一个简单的转换程序,但我一直在阻止用户输入需要整数的字符串:

    choicecheck = 1 
    inputcheck = 1 
    while choicecheck == 1: 
        choice = input ("""please choose type of convert:
        1. Centimeters to inches
        2. Inches to centimeters
        3. Exit""") 


        while inputcheck == 1:
            if choice == "1":
                cm = int(input ("Please type in value in centimeters.")) 
                if type(cm) == int:
                    cmsum = cm * 0.39 # multiplies user input by 0.39
                    print (cm, " centimeters is ", cmsum, " inches") 
                    choicecheck = 0
                    inputcheck = 0
                else:
                     print("Sorry, invalid input")

当谈到inputcheck 时,if 语句的else 部分不起作用,我不知道为什么会这样。请帮忙。

【问题讨论】:

  • type(cm) 永远只能是int,因为cm 是使用对用户输入的int() 的调用构造的。 但是如果用户碰巧输入了一些不能被解释为整数的东西,那么调用就会失败。为此,您可以使用 @mhlester 建议的 try/except 声明。 Python 中很少进行类型检查。

标签: python if-statement while-loop


【解决方案1】:
while True:
    try:
        choice = int(input('please choose type of convert'))
    except ValueError:
        # user entered an input that couldn't be converted to int
        continue
    else:
        if not 1 <= choice <= 3:
            # valid int, invalid choice
            continue
        # success. stop looping
        break

现在您有一个代表他们输入的int。它将继续询问,直到他们成功输入int

【讨论】:

    【解决方案2】:

    这将保持程序循环,直到用户选择退出。我使用浮点数作为第二个用户输入,因为用户可能需要找到 2.5 英寸或类似值的值。

    while True:
        try:
            choice = int(input("""please choose type of convert:
            1. Centimeters to inches
            2. Inches to centimeters
            3. Exit"""))
    
            if choice == 1:
                while True:
                     try:
                        cm = float(input ("Please type in value in centimeters.")) 
                        cmsum = cm * 0.39 # multiplies user input by 0.39
                        print (cm, " centimeters is ", cmsum, " inches")
                        break
                     except ValueError:
                        print('error')
    
            elif choice ==2:
                while True:
                    try:
                        stuff()
                        break
                    except ValueError:
                        print('error')
    
            elif choice == 3:
                print('Thanks!')
                break
    
        except ValueError:
            print('error')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-06
      • 2011-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      • 2015-04-16
      • 2021-08-21
      相关资源
      最近更新 更多