【问题标题】:Ending A Loop in Python 3.x在 Python 3.x 中结束循环
【发布时间】:2016-06-06 04:34:33
【问题描述】:

我正在尝试编写的程序的简要说明。它旨在根据用户输入的初始速度和初始轨迹角度来计算炮弹的轨迹。在程序退出之前,用户有 3 次尝试输入有效输入。如果成功,它将询问用户他们想要计算什么(飞行时间、最大高度或最大水平范围)。然后程序将显示计算出的答案以及用户选择达到最大高度所需的时间。

这两个问题可以在代码中的cmets中找到...

# Constant(s)
GRAV = 9.8

# Accumulator variable(s)
InvalEntry1 = 0
Success = 0

import math

# Defining functions to calculate max height (hMax), total travel time (tTime), and max range (rMax)
def hMax ():
    height = ((iVelocity**2) * math.pow(math.sin(math.radians(iTrajectory)), 2)) / (2 * GRAV)
    return height

def tTime ():
    time = (2* iVelocity * (math.sin(math.radians(iTrajectory)))) / GRAV
    return time

def rMax ():
    rangeMax = ((iVelocity**2) * math.sin(math.radians(2 * iTrajectory))) / GRAV
    return rangeMax

# Assigning user inputs for the initial velocity and initial trajectory to variables
iVelocity = float(input('Please Enter an Initial Velocity Between 20 to 800 m/s: ' ))
iTrajectory = float(input('Please Enter a Initial Trajectory Angle Between 5 to 80 Degrees: '))

print ('\n')


# FIRST PROBLEM... I am having trouble with this loop. If the user enters
# valid numbers on the third attempt, the program will shut down regardless.
# OR if they enter invalid numbers on the third attempt, it will display
# the warning message again, even though they are out of attempts when the
# program should shut down. Lastly, if valid numbers are entered on the
# second attempt, it will continue to the next input function, but will
# still display the warning message.


# Giving the user 3 attempts at providing valid inputs
while (InvalEntry1 < 3):

    # Determining if user inputs are valid
    if (iVelocity < 20) or (iVelocity > 800) or (iTrajectory < 5) or (iTrajectory > 80):
        print ('INVALID ENTRY\n')
        InvalEntry1 = InvalEntry1 + 1
        iVelocity = float(input('Please Enter an Initial Velocity Between 20 to 800 m/s: ' ))
        iTrajectory = float(input('Please Enter a Initial Trajectory Angle Between 5 to 80 Degrees: '))
        print ('\n======================================================================')
        print ('WARNING!!! You have ONE attempt left to input a correct number for')
        print ('initial velocity and initial trajectory before the program will quit.')
        print ('======================================================================\n')

    else:
        # Determining what the user wants to calculate
        print ('What would you like the program to calculate?')
        uCalculate = int(input('Enter 1 for Max Height, 2 for Time, or 3 for Max Horizontal Range: '))
        print ('\n')


        # SECOND PROBLEM... after the user successfully inputs the 
        # correct numbers and the program displays the answers using the 
        # functions, instead of ending the program, it loops back to 
        # the else statement above. I can't seem to figure out how to
        # close the loop and end the program. I tried using
        # while (Success < 1): to close the loop, but it continues to
        # loop anyways.


        # Determining which variable(s) the user wants the program to calculate

        if (uCalculate == 1):
            print ('Maximum Height = %.2f' %(hMax()))
            print ('Total Time = %.2f' %(tTime()))
            Success = Success + 1

        elif (uCalculate == 2):
            print ('Total Time = %.2f' %(tTime()))
            Success = Success + 1

        elif (uCalculate == 3):
            print ('Maximum Horizontal Range = %.2f' %(rMax()))
            print ('Total Flight Time = %.2f' %(tTime()))
            Success = Success + 1

        else:
            print ('INVALID ENTRY')

提前感谢您提供的任何帮助或建议。

【问题讨论】:

  • 请正确缩进您的代码。您发布的内容无法运行。另外,请发布您可以组装的最短代码段,以显示您所询问的问题。
  • 我修复了缩进错误(抱歉,将它从 python 移到这里可能很困难)。如果我进一步分解代码并且您尝试运行它,它会不会因为某些事情不会被定义而给您带来错误?
  • 至少,您不需要 4-case if/elif/else 语句来证明您的问题。这是您可以从minimum, complete, and verifiable example 中删除的那种不必要的细节。
  • 附注:您可以使用简写variable += 1 而不是variable = variable + 1
  • 谢谢大家的建议。我为冗长的混乱代码道歉;这是我的第一堂编程课。我今天已经清理了很多。

标签: python loops python-3.x while-loop


【解决方案1】:

正如前面的评论所提到的,您的代码示例既太长又无法重现。所以我会给你一个更通用的答案,然后你可以用它来修改你的代码。

以更抽象、可重用的术语重述您的问题。您有一个需要用户输入的功能。您希望使用以下内容进行验证:如果输入有效,您希望程序继续。如果输入无效,您要警告用户并重复。如果在尝试 x 次后输入仍然无效,您希望程序退出。这是一种常见的情况,可以使用多种编程习惯用法或模式。这是一个简单的。

首先,将您的输入请求、输入验证和程序代码分成单独的函数。通过这种方式,您可以更轻松地组织和实施您的意图。

其次,在需要检查条件时使用循环半模式,然后在条件为假时继续循环。在其他语言中,您可以使用 do...while 循环来实现这一点,但 Python 只有 while

这里是示例代码。

def get_user_input():
    in1 = input("Please enter height")
    in2 = input("Please enter weight")
    return in1, in2


def validate_user_input(x, y):
    try:
        # validation code for x
        _ = int(x)
    except:
        return False
    try:
        # validation code for y
        _ = int(y)
    except:
        return False

    # if we get here than all inputs are good
    return True


def ask_user():
    # Loop and a half pattern

    max_tries = 3


    val1, val2 = get_user_input()
    tries = 1
    while validate_user_input(val1, val2) is False:
        if tries >= max_tries:
            quit("Max tries exceeded")
        print("Invalid input. Please try again. You have {} attempts remaining".format(max_tries - tries))
        tries += 1
        val1, val2 = get_user_input()

    # if we get here, input is validated and program can continue
    print('Thank You')


if __name__ == '__main__':
    ask_user()

def get_user_input():

【讨论】:

    【解决方案2】:

    添加了 2 个 if 语句来检查 if the last attempt left to display warning messageif the run was Successful to exit program

    请参考###解释cmets

    # Constant(s)
    GRAV = 9.8
    
    # Accumulator variable(s)
    InvalEntry1 = 0
    Success = 0
    
    import math
    
    # Defining functions to calculate max height (hMax), total travel time (tTime), and max range (rMax)
    def hMax ():
        height = ((iVelocity**2) * math.pow(math.sin(math.radians(iTrajectory)), 2)) / (2 * GRAV)
        return height
    
    def tTime ():
        time = (2* iVelocity * (math.sin(math.radians(iTrajectory)))) / GRAV
        return time
    
    def rMax ():
        rangeMax = ((iVelocity**2) * math.sin(math.radians(2 * iTrajectory))) / GRAV
        return rangeMax
    
    
    
    # Assigning user inputs for the initial velocity and initial trajectory to variables
    iVelocity = float(input('Please Enter an Initial Velocity Between 20 to 800 m/s: ' ))
    iTrajectory = float(input('Please Enter a Initial Trajectory Angle Between 5 to 80 Degrees: '))
    
    print ('\n')
    
    
    # FIRST PROBLEM... I am having trouble with this loop. If the user enters
    # valid numbers on the third attempt, the program will shut down regardless.
    # OR if they enter invalid numbers on the third attempt, it will display
    # the warning message again, even though they are out of attempts when the
    # program should shut down. Lastly, if valid numbers are entered on the
    # second attempt, it will continue to the next input function, but will
    # still display the warning message.
    
    
    # Giving the user 3 attempts at providing valid inputs
    while (InvalEntry1 < 3):
    
    
        ### adding if statement to check of the next attempt is last:
        if InvalEntry1 == 2 :
            print ('\n======================================================================')
            print ('WARNING!!! You have ONE attempt left to input a correct number for')
            print ('initial velocity and initial trajectory before the program will quit.')
            print ('======================================================================\n')
    
        # Determining if user inputs are valid
        if (iVelocity < 20) or (iVelocity > 800) or (iTrajectory < 5) or (iTrajectory > 80):
            print ('INVALID ENTRY\n')
            InvalEntry1 = InvalEntry1 + 1
    
    
            iVelocity = float(input('Please Enter an Initial Velocity Between 20 to 800 m/s: ' ))
            iTrajectory = float(input('Please Enter a Initial Trajectory Angle Between 5 to 80 Degrees: '))
    
        else:
            # Determining what the user wants to calculate
            print ('What would you like the program to calculate?')
            uCalculate = int(input('Enter 1 for Max Height, 2 for Time, or 3 for Max Horizontal Range: '))
            print ('\n')
    
    
            # SECOND PROBLEM... after the user successfully inputs the 
            # correct numbers and the program displays the answers using the 
            # functions, instead of ending the program, it loops back to 
            # the else statement above. I can't seem to figure out how to
            # close the loop and end the program. I tried using
            # while (Success < 1): to close the loop, but it continues to
            # loop anyways.
    
    
            # Determining which variable(s) the user wants the program to calculate
    
            if (uCalculate == 1):
                print ('Maximum Height = %.2f' %(hMax()))
                print ('Total Time = %.2f' %(tTime()))
                Success = Success + 1
    
            elif (uCalculate == 2):
                print ('Total Time = %.2f' %(tTime()))
                Success = Success + 1
    
            elif (uCalculate == 3):
                print ('Maximum Horizontal Range = %.2f' %(rMax()))
                print ('Total Flight Time = %.2f' %(tTime()))
                Success = Success + 1
    
            else:
                print ('INVALID ENTRY')
    
                ### i advice to add here  InvalEntry1 += 1   
                #InvalEntry1 = InvalEntry1 + 1
    
            ### if success - exit while loop
    
            if Success > 0 :
                print ('Goodbye')
                break
    

    【讨论】:

    • 根据我的最小更改政策
    猜你喜欢
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 2019-03-06
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    相关资源
    最近更新 更多