【问题标题】:While loop runs continuously in Python, good input or bad?虽然循环在 Python 中连续运行,输入好还是坏?
【发布时间】:2016-07-19 07:33:30
【问题描述】:

我正在编写一个向用户询问百分比的代码,并一直询问直到用户输入可接受的输入。但是,当我运行它时,无论我输入哪种输入,while 循环都不会中断。

这是我的代码:

import math

while True:
    try:
        entered = float(raw_input("Please enter the velocity (as a percentage of the speed of light): "))
    except ValueError:
        print("Sorry, an acceptable input was not entered. Try again.")
        continue

    if entered > 100:
        print("Sorry, a velocity greater than the speed of light cannot be used. Try again.")
        continue
    elif entered <= 0:
        print("Sorry, a percent cannot be negative. Try again.")
        continue
    else:
        #the percent entered is valid, break out of while loop
        break

print("Ship is traveling at ", entered, "% the speed of light.")
print("  ")

speedOfLight = 299792458                         #speed of light constant
percentage = entered / 100                       #turn entered percent into decimal
speed = speedOfLight * percentage                #actual speed (in m/s)         
denominator = math.sqrt(1 - (percentage ** 2))   #denominator of factor equation
factor =  1 / denominator                        #solve for given factor equation

shipWeight = 70000 * factor                      #given ship weight * factor
alphaCentauri = 4.3 / factor                     # given times divided by the factor
barnardsStar = 6.0 / factor
betelgeuse = 309 /factor
andromeda = 2000000 / factor

print("At this speed: ")
print("    Weight of the shuttle is ", shipWeight)
print("    Perceived time to travel to Alpha Centauri is ", alphaCentauri, " years.")
print("    Perceived time to travel to Barnard's Star is ", barnardsStar, " years.")
print("    Perceived time to travel to Betelgeuse is ", betelgeuse, " years.")
print("    Perceived time to travel to Andromeda Galaxy is ", andromeda, " years.")

【问题讨论】:

  • 请花时间修复缩进,以便我们为您提供帮助。

标签: python input error-handling while-loop break


【解决方案1】:

您正在检查except 中的数据输入。除非对float 的强制转换引发ValueError,否则你永远不会进入你的内部。

您只是想将条件移出except 块,以便检查通过float 转换的数据:

while True:
    try:
        entered = float(input("Please enter the velocity (as a percentage of the speed of light): "))
    except ValueError:
        print("Sorry, an acceptable input was not entered. Try again.")
        continue

    if entered > 100:
        print("Sorry, a velocity greater than the speed of light cannot be used. Try again.")
        continue
    elif entered <= 0:
        print("Sorry, a percent cannot be negative. Try again.")
        continue
    else:
        #the percent entered is valid, break out of while loop
        break

【讨论】:

  • 我认为(希望)编辑把它搞砸了,因为它是问题中写的无效语法
【解决方案2】:

您的缩进有点不稳定,代码永远不会到达break 语句,因为您在此之前continue 循环。幸运的是,您可以使用和 else 关键字使其工作:

while True:
    try:
        entered = float(raw_input("Please enter the velocity (as a percentage of the speed of light): "))
    except ValueError:
        print("Sorry, an acceptable input was not entered. Try again.")
        continue
    else: # no exception
        if entered > 100:
            print("Sorry, a velocity greater than the speed of light cannot be used. Try again.")
            continue
        elif entered <= 0:
            print("Sorry, a percent cannot be negative. Try again.")
            continue
        else:
            #the percent entered is valid, break out of while loop
            break

【讨论】:

  • 是的,我在这个网站上输入代码时总是弄乱缩进。但谢谢你,它就像一个魅力!
  • @Clarisa 一旦你习惯了缩进,python 就是设计最完善的语言之一。享受它:)
【解决方案3】:

您甚至不需要继续/中断来完成这项工作。您还需要“导入数学”,一旦您最终跳出 while 循环,这将很重要。

您需要做的是观察缩进。 try/except 不在位置 - 如果这反映了代码的实际编写方式,这将解释您永无止境的 while 循环。

只有缩进修复和“导入数学”

import math

valid = False

while not valid:
    try:
            entered = float(raw_input("Please enter the velocity (as a percentage of the speed of light): "))
    except ValueError:
            print("Sorry, an acceptable input was not entered. Try again.")
            continue

    if entered > 100:
        print("Sorry, a velocity greater than the speed of light cannot be used. Try again.")
    elif entered <= 0:
        print("Sorry, a percent cannot be negative. Try again.")
    else:
        #the percent entered is valid, break out of while loop
            valid = True

print("Ship is traveling at ", entered, "% the speed of light.")
print("  ")

speedOfLight = 299792458                         #speed of light constant
percentage = entered / 100                       #turn entered percent into decimal
speed = speedOfLight * percentage                #actual speed (in m/s)         
denominator = math.sqrt(1 - (percentage ** 2))   #denominator of factor equation
factor =  1 / denominator                        #solve for given factor equation

shipWeight = 70000 * factor                      #given ship weight * factor
alphaCentauri = 4.3 / factor                     # given times divided by the factor
barnardsStar = 6.0 / factor
betelgeuse = 309 /factor
andromeda = 2000000 / factor

print("At this speed: ")
print("    Weight of the shuttle is ", shipWeight)
print("    Perceived time to travel to Alpha Centauri is ", alphaCentauri, " years.")
print("    Perceived time to travel to Barnard's Star is ", barnardsStar, " years.")
print("    Perceived time to travel to Betelgeuse is ", betelgeuse, " years.")
print("    Perceived time to travel to Andromeda Galaxy is ", andromeda, " years.")

【讨论】:

    猜你喜欢
    • 2022-09-30
    • 2012-04-26
    • 2021-12-14
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 2020-03-17
    • 2019-08-26
    相关资源
    最近更新 更多