python - 验证值仍然导致类型错误?

标签 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()

最佳答案

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

calculate_distance(int(n))

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

return(int(input_string))

关于python - 验证值仍然导致类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53233647/

相关文章:

javascript - 添加按钮按下时的输入值检查

c# - 要么或要求验证

validation - 来自通过 ActiveForm 分配的标签的 Yii2 模型验证消息

Python 平方根

javascript - "place"在此 for 循环中意味着什么

python - 如何仅用 NA 替换前导零?

php - 选择比较另一个表中的字段的记录

java - GUI 在 Java 的 While 循环期间卡住

python - 计算数据帧中的主题标签频率

python - 如何将字符串 (uri) 拆分为 Python 中的嵌套字典