【问题标题】:Check if number is prime with Python thowing an exception检查数字是否为素数,Python抛出异常
【发布时间】:2023-04-08 22:06:01
【问题描述】:

我有一个python函数,它应该采用整数参数并根据函数中的逻辑对其进行处理,并打印出该数字是否为素数。 我在 Visual Studio 2019 上运行我的 python 文件。它在参数上抛出异常,从用户传递到函数中。这是我到目前为止从 Visual Studio 异常框unsupported operand type(s) for +: 'int' and 'str'

##Defining python function to check whether a certain number is prime or not
def check_Prime(o):
    isPrime=True
    for i in range(2,o):
        if(o%i==0):
          isPrime=False
    
    if(isPrime):
        print(o+" "+"is prime")
    else:
        print(o+" "+"is not prime")


prime=int(input("Enter the integer you would like to check for prime"))
check_Prime(prime)

【问题讨论】:

  • print(f"{o} is prime")

标签: python function input


【解决方案1】:

使用f-strings or formatted string literals:

print(f'{o} is prime')

您的错误指向连接 intstr,这是您无法做到的。

【讨论】:

  • 谢谢你,我一开始并没有理解它,但现在我发现它是条件结构中的打印语句
猜你喜欢
  • 2013-08-23
  • 1970-01-01
  • 2011-09-21
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 2013-03-22
  • 1970-01-01
  • 2018-04-24
相关资源
最近更新 更多