首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >嵌套的while循环- Python

嵌套的while循环- Python
EN

Stack Overflow用户
提问于 2014-02-07 04:33:28
回答 2查看 1.6K关注 0票数 1

我正在开发一个简单的转换程序,但我遇到了阻止用户键入需要整数的字符串的问题:

代码语言:javascript
复制
    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部分无法工作,我不知道原因。请帮帮忙。

EN

回答 2

Stack Overflow用户

发布于 2014-02-07 04:36:11

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2014-02-07 05:03:09

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

代码语言:javascript
复制
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')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21613455

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档