【问题标题】:Getting only Numeric values as input in python - providing response for string values在python中仅获取数字值作为输入 - 为字符串值提供响应
【发布时间】:2021-05-07 11:26:00
【问题描述】:

下面是我的代码。我试图在代码输入时循环这个,所以如果有人给出了数字以外的任何东西,那么它必须用下面的消息做出响应,然后再次询问数字。但是我被卡住了,它尝试了许多尝试块的变体..但是输出似乎是数字是否有效,然后它给出响应[素数或非素数]以及关于非数字的辅助打印值以及输入是否是非数字的,它会给出一个错误,因为它是非数字......任何帮助或建议请

def prime_checker(number) :
    is_prime = True
    for i in range(2, number) :
        if number % i == 0 :
            is_prime = False
    if is_prime :
        print("It's a prime number")
    else :
        print("Its not a prime number")

should_continue = True
num = int(input("Check this number: "))
prime_checker(number=num)
while not num == int():
    result = input("You have entered a non numeric value, please enter a number to continue else enter 'no' to exit. '.\n")
    if result == "no":
        should_continue = False
        print("Goodbye")

【问题讨论】:

  • 这里是响应:检查这个数字:40 它不是一个素数您输入了一个非数字值,请输入一个数字继续否则输入'no'退出。 '。

标签: python for-loop oop while-loop integer


【解决方案1】:

您应该检查变量的类型,而不是变量本身:

  ...
  while not isinstance(num, int):
  ....

【讨论】:

    【解决方案2】:

    你不能拥有while not num == int() 你可以拥有num.isdigit() == False。请记住,当您使用输入时,您会收到一个字符串。您需要一个try: except: 块来处理int(num) 检查或使用num.isdigit()。您没有在任何有意义的地方使用您的 should_continue 变量。您需要使用break 命令退出while loop

    更改了代码以使其更合理

    【讨论】:

    • 当我运行代码时,请出现以下错误。 : num = int(input("Check this number: ")) ValueError: invalid literal for int() with base 10: 'yes
    猜你喜欢
    • 1970-01-01
    • 2022-01-05
    • 2018-03-14
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    相关资源
    最近更新 更多