如何根据特定条件触发内循环(Python)

时间:2017-10-29 04:14:42

标签: python loops while-loop

我是Python新手,也是一般编程人员。我一直在写一个温度转换器,作为练习我学到的一些概念的方法。到目前为止我所写的内容总体上运作良好,但我已经在我想要实现的特定目标上打了一堵砖墙:

当用户做出可接受的第一选择(“F到C”或“C到F”,而不是其他任何东西)时,他们会得到下一个问题,即他们想要转换的温度。在这里我也确保程序不会给出错误消息并在人输入除整数或浮点数以外的任何内容时停止,但是如果发生这种情况,我不希望程序一直循环到开头,但仅限于决策树特定分支的开头。

换句话说,当有人说他们想要将华氏温度值转换为摄氏温度然后键入“jambalaya”而不是“78”时,我希望程序让他们在同一个“再次输入一个值”华氏度到摄氏度“选择分支,而不是询问他们是否要将F转换为C或C转换为F,这是该程序目前正在进行的操作。

(只是快速说明:我希望程序继续询问此人是否想要从F转换为C或C转换为F,如果此人已成功获得转换后的值。)

这是我写的代码:

def temperature():
while True:
    selection = input ('Choose your conversion ("F to C" or "C to F"): ')
    if selection == 'F to C':
        num = input ('Enter a temperature in °F: ')
        try:
            float(num)
            r = round(float(num))
            s = (r-32)*(5/9)
            print (r,'°F is ',round(s),'°C')
            if s > 30:
                print ('A little hot out there!')
            elif s < 5:
                print ('Make sure to wear a jacket!')
            else:
                print ('Have a nice day!')
        except:
            print ('Please enter only numbers') 
    elif selection == 'C to F':
        num = input ('Enter a temperature in °C: ')
        try:
            float(num)
            r = round(float(num))
            s = (r*9/5)+32
            print (r,'°C is ',round(s),'°F')
            if s > 86:
                print ('A little hot out there!')
            elif s < 41:
                print ('Make sure to wear a jacket!')
            else:
                print ('Have a nice day!')
        except:
            print ('Please enter only numbers')
    else:
        print ('Please make a valid selection')
temperature()

您如何修改此代码以实现我上面描述的结果?

4 个答案:

答案 0 :(得分:0)

最简单的方法是在程序中添加另一个循环,以便让用户输入正确的值。一旦用户输入了正确的值,它就会使用break退出循环。

def temperature():
while True:
    selection = input ('Choose your conversion ("F to C" or "C to F"): ')
    if selection == 'F to C':
        while True: # *** Wrap this code in a loop
            num = input ('Enter a temperature in °F: ')
            try:
                float(num)
                r = round(float(num))
                s = (r-32)*(5/9)
                print (r,'°F is ',round(s),'°C')
                if s > 30:
                    print ('A little hot out there!')
                elif s < 5:
                    print ('Make sure to wear a jacket!')
                else:
                    print ('Have a nice day!')

                break # *** Break out of the loop after a success
            except:
                print ('Please enter only numbers') 
    elif selection == 'C to F':
        while True:
            num = input ('Enter a temperature in °C: ')
            try:
                float(num)
                r = round(float(num))
                s = (r*9/5)+32
                print (r,'°C is ',round(s),'°F')
                if s > 86:
                    print ('A little hot out there!')
                elif s < 41:
                    print ('Make sure to wear a jacket!')
                else:
                    print ('Have a nice day!')

                break
            except:
                print ('Please enter only numbers')
    else:
        print ('Please make a valid selection')
temperature()

因为它可能很容易辨别,这开始让事情变得杂乱无章。将F到C和C的代码转换为F并将其移动到自己的函数中可能是个好主意。

答案 1 :(得分:0)

您可以在这里做的一件事就是将while循环与try结合起来。可能新的想法是测试对象类型。

num = ''
while not type(num) == float:
    try:
        num = float(num)
    except:
        num = input('Enter a temperature in °F: ')

答案 2 :(得分:0)

试试这个,这满足了你的所有要求

  1. 在按q
  2. 之前,它会不断询问用户他/她想要进行何种转换
  3. 如果他们没有再次输入F或C提示
  4. 如果他们没有再次输入浮点数提示
  5. 区分大小写是删除方式接受F / f到C / c

    window.onLoad(window.scrollTo(x, y));

    def temperature():
        selection = input ('Choose your conversion ("F to C" or "C to F"): or Q to quit ')

    if selection.lower() == 'f to c': while True: try: num = float(input ('Enter a temperature in °F: ')) r = round(float(num)) s = (r-32)*(5/9) print (r,'°F is ',round(s),'°C') if s > 30: print ('A little hot out there!') elif s < 5: print ('Make sure to wear a jacket!') else: print ('Have a nice day!') return True except ValueError: print ('Please enter only numbers') elif selection.lower() == 'c to f': while True: try: num = float(input ('Enter a temperature in °C: ')) r = round(float(num)) s = (r*9/5)+32 print (r,'°C is ',round(s),'°F') if s > 86: print ('A little hot out there!') elif s < 41: print ('Make sure to wear a jacket!') else: print ('Have a nice day!') return True except ValueError: print ('Please enter only numbers') elif selection == 'Q': return False else: print ('Please make a valid selection')

答案 3 :(得分:0)

出于您的目的,我建议您编写单独的函数来计算转换,以便您可以递归调用它

# first of all let's define how many invalid attempt you want to allow to user.
MAX_INCORRECT_ATTEMPT = 5

def f_to_c(attempt=0):
    """
    convert °F to °C
    """
    try:
        num = float(input ('Enter a temperature in °F: ')) # take input and convert it to float if exception occurs it will be handled
        r = round(num)
        s = (r-32)*(5/9)
        print (r,'°F is ',round(s),'°C')
        if s > 30:
            print ('A little hot out there!')
        elif s < 5:
            print ('Make sure to wear a jacket!')
        else:
            print ('Have a nice day!')
        return True # returns True if act of user is valid as expected
    except ValueError: # to only handle valueerror caused only if user enters invalid input like string or any special character
        # it is good habit to precise which exception you are handling so I have specified ValueError arise in python3 when conversion of input is not possible
        attempt += 1 # well here we increse invalid attempt count
        print ('Please enter only numbers..')
        if attempt > MAX_INCORRECT_ATTEMPT:
            return False
        else:
            return f_to_c(attempt) # pass the invalid attempt count to function argument


def c_to_f(attempt=0):
    """
    convert °C to °F
    """
    try:
        num = float(input('Enter a temperature in °C: '))
        r = round(num)
        s = (r*9/5)+32
        print("{} °C is {} °F".format(r, round(s)))
        if s > 86:
            print ('A little hot out there!')
        elif s < 41:
            print ('Make sure to wear a jacket!')
        else:
            print ('Have a nice day!')
        return True
    except ValueError:
        attempt += 1 # calculating attempt so we can end the program if user exceeds allowed limit of faults
        print ('Please enter only numbers..')
        if attempt > MAX_INCORRECT_ATTEMPT:
            return False
        else:
            return c_to_f(attempt)


def temperature_converter():
    while True:
        selection = input ('\nChoose your conversion \n1- "F to C" \n2- "C to F"\n3- Quit\n> ')
        if selection == '1':
            status = f_to_c() # store the value returned by function in status
            if not status: # the block only executes if function return False
                print("too many incorrect attempt... bye...")
                break
        elif selection == '2':
            stat = c_to_f()
            if not stat:
                print("too many incorrect attempt... bye...")
                print("bye...")
                break
        elif selection == "3":
            print("bye...")
            break
        else:
            print ('Please make a valid selection.')

temperature_converter()

输出:

Choose your conversion
1- "F to C"
2- "C to F"
3- Quit
> 1
Enter a temperature in °F: sd
Please enter only numbers..
Enter a temperature in °F: 25
25 °F is  -4 °C
Make sure to wear a jacket!

Choose your conversion
1- "F to C"
2- "C to F"
3- Quit
> 3
bye...