【问题标题】:Python while loop not endingPython while循环没有结束
【发布时间】:2015-09-14 15:43:28
【问题描述】:

我遇到了一些 while 循环 问题。我的目标是在用户输入负值 3 次时使 while 循环结束。问题是当我收到第三条消息时,它并没有像它应该的那样以“milesLoop”结尾 (我尝试使用一个循环,但我想使用多个循环进行测试) 这可能是一个容易解决的问题,但我被卡住了。

这是python代码:

__author__ = 'MichaelCorbett'
import sys

print('Michael Corbett converter ')
print('\n')

milesLoop = 1
fhietLoop = 1
gallonLoop = 1
poundsLoop = 1
inchesLoop = 1

while milesLoop == 1:

    miles = float(input('What\'s up Will, how many miles do you wish to convert to Kilometers? '))
    if miles < 0:
        print('This converter does not accept negeative values. Try again!')

        miles = float(input('What\'s up Will, how many miles do you wish to convert to Kilometers? '))
        if miles < 0:
            print('This converter does not accept negeative values. Try again')

            miles = float(input('What\'s up Will, how many miles do you wish to convert to Kilometers? '))
            if miles < 0:
                print('This converter does not accept negeative values. Program is Terminated')
                milesLoop = 2


                while fhietLoop == 1:

                    Fheit = float(input('What temperature is it outside in Fahrenheit? '))
                    if Fheit < 0 and Fheit > 1000:
                        print('This converter does not accept negeative values.')

                        Fheit = float(input('What temperature is it outside in Fahrenheit? '))
                        if Fheit < 0 and Fheit > 1000:
                            print('This converter does not accept negeative values.')

                            Fheit = float(input('What temperature is it outside in Fahrenheit? '))
                            if Fheit < 0 and Fheit > 1000:
                                print('This converter does not accept negeative values. Program is Terminated')
                                fhietLoop = 2


                            while gallonLoop == 1:

                                gallon = float(input('How many gallons are you trying to convert? '))
                                if  gallon < 0:
                                    print('This converter does not accept negeative values.')

                                    gallon = float(input('How many gallons are you trying to convert? '))
                                    if  gallon < 0:
                                        print('This converter does not accept negeative values.')

                                        gallon = float(input('How many gallons are you trying to convert? '))
                                        if  gallon < 0:
                                            print('This converter does not accept negeative values. Program Terminated')
                                            gallonLoop = 2


                                        while poundsLoop == 1:

                                            pounds = float(input('How many pounds would you like to convert? '))
                                            if  pounds < 0:
                                                print('This converter does not accept negeative values.')

                                                pounds = float(input('How many pounds would you like to convert? '))
                                                if  pounds < 0:
                                                    print('This converter does not accept negeative values.')

                                                    pounds = float(input('How many pounds would you like to convert? '))
                                                    if  pounds < 0:
                                                        print('This converter does not accept negeative values. Program Terminated')
                                                        poundsLoop = 2


                                                    while inchesLoop == 1:

                                                        inches = float(input('How many inches would you like to convert? '))
                                                        if  inches < 0:
                                                            print('This converter does not accept negeative values.')

                                                            inches = float(input('How many inches would you like to convert? '))
                                                            if  inches < 0:
                                                                print('This converter does not accept negeative values.')

                                                                inches = float(input('How many inches would you like to convert? '))
                                                                if  inches < 0:
                                                                    print('This converter does not accept negeative values. Program Terminated')
                                                                    inchesLoop = 2



                                                                # Calculations

                                                                kilometers = miles * 1.6
                                                                celsius = int((Fheit - 32) * 5/9)
                                                                liters = gallon * 3.9
                                                                kilograms = pounds * .45
                                                                centimeters = inches * 2.54

                                                                # Output

                                                                print('\n')
                                                                print(miles,  ' miles is ',  kilometers,  ' Kilometers')
                                                                print('Its is ', celsius, 'Celsius outside.')
                                                                print(gallon,  ' gallons is ',  liters,  ' liters')
                                                                print(pounds,  ' pounds is ',  kilograms,  ' kilograms')
                                                                print(inches,  ' inches is ',  centimeters,  ' centimeters')

【问题讨论】:

  • 哇,你现在可能想重组你的代码,为什么?因为它嵌套得像疯了一样,你甚至无法调试由简单的ifs 和whiles 组成的自己的代码
  • 这是相当多的代码,需要大量复制(例如使用每个if 语句三次),请将其缩小到重现此错误的最少代码。
  • 当用户预先输入一个正值时,您认为您的代码会做什么?
  • import this(第 5 行)

标签: python if-statement while-loop


【解决方案1】:
def get_float(prompt):
    while True:
       try:
          return float(input(prompt))
       except:
          print "Thats not a number!"


def get_positive_number(prompt,tries=3):
    for i in range(tries):
         result = get_float(prompt)
         if result >= 0: return result
         print "Sorry Negative not allowed %d/%d"%(i,tries)

while True:
     result = get_positive_number("How Many Gallons?")
     if result is None: 
        print "OK DONE"
        break
     print "Convert %0.2f Gallons"%(result)

【讨论】:

    【解决方案2】:
    __author__ = 'MichaelCorbett'
    import sys
    
    def myLoop(question, tries = 0):
        while True: 
            if tries == 3:
                sys.exit()
            user_in = float(input(question))
            if user_in < 0:
                print('This converter does not accept negeative values. Try again!')
                tries += 1
            else:
                return user_in
    
    print('Michael Corbett converter\n')
    
    miles = myLoop('What\'s up Will, how many miles do you wish to convert to Kilometers?')
    Fheit = myLoop('What temperature is it outside in Fahrenheit?')
    gallon = myLoop('How many gallons are you trying to convert?')
    pounds = myLoop('How many pounds would you like to convert?')
    inches = myLoop('How many inches would you like to convert?')
    
    # Calculations
    
    kilometers = miles * 1.6
    celsius = int((Fheit - 32) * 5/9)
    liters = gallon * 3.9
    kilograms = pounds * .45
    centimeters = inches * 2.54
    
    print('\n{0} miles is {1} Kilometers'.format(miles, kilometers))
    print('Its is {0} Celsius outside.'.format(celsius))
    print('{0} gallons is {1} liters'.format(gallon, liters))
    print('{0} pounds is {1} kilograms'.format(pounds, kilograms))
    print('{0} inches is {1} centimeters'.format(inches, centimeters))
    

    【讨论】:

    • 1) 您有 5 个函数做几乎相同的事情,因此可以将它们替换为一个接受所需转换类型参数的函数。 2)当你可以用一个简单的循环做同样的事情时,为什么要使用递归?递归有额外的开销,最好在 Python 中避免,除非它对于问题域是自然的,例如使用递归数据结构,如树。 3)“否定”只有一个“e”。
    • 是的,这可以重写为一个函数。我复制粘贴了文本,所以那里可能有错别字。这些递归使用尾调用优化来避免为递归函数分配新的堆栈帧。
    • Python 没有尾调用优化。我意识到拼写错误是由于复制粘贴造成的,但这并不妨碍您修复它。 :) OTOH,您当然没有义务修复此类错误。
    • 没有意识到 python 没有尾调用优化。我想用动态语言实现起来太复杂了。学到了一些新东西;)
    • 是的,要让 TCO 在所有情况下都有效会很棘手。但主要是因为 TCO 会干扰堆栈跟踪。请参阅this answer 及其链接了解更多信息。
    猜你喜欢
    • 2017-04-03
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 2020-01-17
    • 2018-04-06
    • 2014-03-15
    相关资源
    最近更新 更多