简体   繁体   English

Python素数检查器不起作用

[英]Python Prime number checker not working

I'm trying to build a simple Prime Number checker in Python 3.x and I'm running into some issues. 我试图在Python 3.x中构建一个简单的质数检查器,但遇到了一些问题。 I will post my code and then explain my difficulties. 我将发布代码,然后解释我的困难。

number = input("Please enter a number: ")

is_prime = True;

for factor in range(2, number):
    if number % factor == 0:
        is_prime = False;

if is_prime == True:
    print("%d is a prime number!") % number
else:
    print ("%d is NOT a prime number!") % number 

Now when I run the following code, I get this error: 现在,当我运行以下代码时,出现此错误:

C:\\Users\\clark\\Documents\\Python Projects>python PrimeNumberChecker.py Please enter a number: 4 Traceback (most recent call last): File "PrimeNumberChecker.py", line 5, in for factor in range(2, number): TypeError: 'str' object cannot be interpreted as an integer C:\\ Users \\ clark \\ Documents \\ Python Projects> python PrimeNumberChecker.py请输入一个数字:4追溯(最近一次通话是最后一次):文件“ PrimeNumberChecker.py”,第5行,因数在range(2,number)中:TypeError:'str'对象不能解释为整数

Now, from my limited understanding of Python the input method that I'm using to evaluate the number variable should return an integer so I'm not sure why it's telling me there's a conversion issue. 现在,由于我对Python的有限理解,我用来评估number变量的输入法应该返回一个整数,因此我不确定为什么它告诉我存在转换问题。 Could anybody shed some light on what's going on here? 有人可以阐明这里发生的事情吗? I'm very new to Python. 我是Python的新手。

Thanks 谢谢

In Python 3.x, you need to convert your variable number to int like this: 在Python 3.x中,您需要像下面这样将变量number转换为int

number = int(input("Please enter a number: "))

See these two examples from the two version of Python that I have on my machine: 请参阅我的计算机上的两个Python版本中的以下两个示例:

In Python 3.4: 在Python 3.4中:

>>> number = input("Please enter a number: ")
Please enter a number: 4
>>> type(number)
<class 'str'>

In Python 2.7: 在Python 2.7中:

>>> number = input("Please enter a number: ")
Please enter a number: 4
>>> type(number)
<type 'int'>

Please take a look at this important answer of How can I read inputs as integers in Python? 请查看以下重要答案: 如何在Python中将输入读取为整数?

In python2.x python2.x

number = input("Please enter a number: ")  

number will be a int . number将是一个int But in python3.x it will be str . 但是在python3.x它将是str You are using python.3x so you have to convert that into integer. 您正在使用python.3x因此必须将其转换为整数。 with using int . 使用int

number = int(number)

Might be you are referenced a code which is wrote in python2.x 可能是您引用了在python2.x编写的代码

You could try this one 你可以试试这个

number=int(input("please enter a number")

counter=0

for factor in range (1,number):
     if number%factor==0:
        counter=counter+1

if counter==2:
  print(number,"is prime")
else:
  print(number,"is not prime")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM