【问题标题】:While loop to continuously prompt user to provide correct input typeWhile 循环不断提示用户提供正确的输入类型
【发布时间】:2019-02-08 01:24:00
【问题描述】:

我有一个家庭作业问题,我需要在我的函数中添加一个 while 循环,如果最初输入的值不是数字,它将让用户 3 次额外尝试输入另一个值。代码的原始功能是确定三角形或梯形的面积。

loopCount = 0
# The "while" statement keeps looping until its condition (loopCount<4) made False.
while loopCount<4:
    # loopCount will increase 1 for each loop
    loopCount += 1

虽然我什至不确定在我的代码中将上述行放在哪里。

    # This program calculates the area of a triangle or trapezoid

    # Statement: print function outputs the statement on screen  
    print("This program finds the area of a triangle or trapezoid.")
    print()

    # Module: math module imported
    import math

    # Determine the objects shape
    print("Please enter the shape from the following menu")
    print("Triangle = type 1")
    print("Trapezoid = type 2")

    # If user types a number other than 1 or 2, this will prompt them again to pick a valid choice
    user_input = 0
    while user_input not in (1,2) :
            user_input = int(input("Enter your choice: "))

    # Variables: asigns new value to a variable depending on which shape we are caluclating the area of
    if (user_input == 1):
        print("Alright, you want to calculate the area of a triangle: ")
        height = float(input("Please enter the height of the triangle: "))
        base = float(input("Please enter the base length of the triangle: "))

    if (user_input == 2):
        print("Alright, you want to calculate the area of a trapezoid: ")
        base_1 = float(input("Please enter the base length of the trapezoid: "))
        base_2 = float(input("Please enter the second base length of the trapezoid: "))
        height = float(input("Please enter the height of the trapezoid: "))

    # Expression and operators: calculates area based on shape choosen.  Triangle_area = (base*height)/2, Trapezoid_area = ((base1+base2)/2)*height
    if (user_input == 1):
        area_triangle = 0.5 * height * base
    if (user_input == 2):   
        area_trapezoid = ((base_1+base_2)/2)*height

    # Function: math function returns a statement defining the height, base(s) and area of the triangle or trapezoid
    if (user_input == 1):
        print("The area of a triangle with height", height, "and base", base, "is", area_triangle)

    if (user_input == 2): 
        print("The area of a trapezoid with height", height, ", base 1", base_1, "and base 2", base_2, "is", area_trapezoid)

    If the user enters a value that could not be converted to numeric type, allow 3 additional opportunities to enter a new value. If the user fails to enter a correct value after 4 attempts, inform them of such failure and allow the program to end without crashing.

【问题讨论】:

  • 欢迎来到stackoverflow。代码中有几个地方是用户输入值的地方。您应该允许哪一个重试?到目前为止,您尝试过什么?
  • 在输入基数或高度的非数字值时,我需要允许重试。我试图合并上面的循环函数(代码的第一行),但是如果输入的值不是数字,我会一直坚持如何运行循环。
  • 允许最多 3 次重试是什么意思?尝试用 if/then/else 来描述(英文,不用写代码)。一旦你这样做了,如何使用 while 语句可能会变得更加明显。
  • 如果输入不是数字,则打印“请尝试输入有效数字:”如果输入是数字,则继续执行其余代码以计算面积。非常感谢您的帮助。

标签: python loops input while-loop


【解决方案1】:

float() 无法将值转换为浮点数或OverflowError 时,您可以在输入上使用try/except 来处理ValueError "如果参数超出 Python 的范围浮动"。

loopCount = 0
while loopCount < 4:
    try:
        height = float(input("Please enter the height of the triangle: "))
        break
    except:
        print("That is not a number.")
        loopCount += 1 

if loopCount == 4:
    print("You failed to input valid values")
    # return with an error or maybe abort with sys.exit(1)
else:
    print("Great! I can now compute stuff.")

您可以在try 块内一次检查所有输入(如果您不关心哪一个具体无效或者您不需要向用户指出):

loopCount = 0
while loopCount < 4:
    try:
        base_1 = float(input("Please enter the base length of the trapezoid: "))
        base_2 = float(input("Please enter the second base length of the trapezoid: "))
        height = float(input("Please enter the height of the trapezoid: "))
        break
    except:
        print("One of the inputs is not a number.")
        loopCount += 1 

if loopCount == 4:
    print("You failed to input valid values")
    # return with an error or maybe abort with sys.exit(1)
else:
    print("Great! I can now compute stuff.")

为了避免大量重复的try-except,我建议创建一个获取浮点输入(或所有输入)的方法,然后从您的主方法中调用它。

【讨论】:

    猜你喜欢
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    相关资源
    最近更新 更多