经过验证的值仍然会导致TypeError吗?

时间:2018-11-09 21:47:31

标签: python loops validation input while-loop

继续遇到此错误,但我感到困惑,因为从理论上讲,在通过函数作为参数发送变量之前,我已经将变量验证为整数。有任何想法吗?谢谢!

函数的问题是:“ calculate_distance(n):”,这不像我在使用带有这些值的“ <>”运算符一样。

print("Welcome Astronaut to Apollo 11 - the mission to land on The Moon.")
print("Lets determine the length of your journey so far - It should take about 3 days to reach Lunar orbit.")

# Function Boolean valid_integer(String input_string)
#   Declare Boolean is_valid
#
#   is_valid = is input_string a valid integer?
#   Return is_valid
# End Function

def valid_integer(input_string):
    try:
        val = int(input_string)
        is_valid = True
    except ValueError:
        is_valid = False
    return is_valid

# Function Integer get_number()
#   Declare String input_string
#   Declare Boolean is_valid
#
#   Display "Enter a number: "
#   Input input_string
#   Set is_valid = valid_integer(input_string)
#   While Not is_valid
#       Display "Please enter a whole number: "
#       Input input_string
#       is_valid = valid_integer(input_string)
#   End While
#   input_integer = int(input_string)
#   Return input_integer
# End Function

def get_number():
    input_string = input("Enter your hours of spaceflight: ")
    is_valid = valid_integer(input_string)
    while not is_valid:
        input_string = input("Please enter a whole number: ")
        is_valid = valid_integer(input_string)
    input_integer = int(input_string)
    return input_string


def output_distance(counter, distance, percent):
    print("Since hour", counter, "you have traveled", distance, "miles,", percent, "of the way there")

def calculate_distance(n):
    counter = 0
    distance = 0
    percent = 0

    if(n < 1):
        print("You're still on the launchpad")
        return
    if(n > 72):
        print("You made it! The Eagle has landed")
        return
    while counter < n:
        counter = counter + 1
        distance = counter * 3333
        percent = ((counter * 3333) / 240000) * 100
        output_distance(counter, distance, percent)


# Module main()
#   Set n = get_number()
#   Call calculate(n)
# End Module

def main():
    n = get_number()
    calculate_distance(n)

main()

2 个答案:

答案 0 :(得分:1)

即使您在valid_integer()函数中将数字验证为整数,也可以将数字作为整数传递给calculate_distance()函数。

calculate_distance(int(n))

或者在此过程中的其他任何时候。在get_number()函数中返回它,例如:

return(int(input_string))

答案 1 :(得分:0)

使用int(输入)作为输入数字