如何划分存储在变量中的数字?

时间:2016-08-09 19:25:39

标签: python

我正在编写的程序允许您输入任何数字,程序将识别该数字是否为素数。但是,我收到的错误如下所示。

我在使用这行代码时遇到了问题:

chosen = input("Input a number")
number = (chosen) / chosen

当我运行它时,这是输出:

Input a number1
Traceback (most recent call last):
File "C:\Users\engineer2\Desktop\Programs\prime numbers.py", line 3, in <module>
number = (chosen) / chosen
TypeError: unsupported operand type(s) for /: 'str' and 'str'

以下是完整代码:

chosen = input("Input a number")
number = (chosen) / chosen
one = 1
if number == (one):
print ("Its a prime number")


else:
print ("Not a prime")



input ("press enter")

4 个答案:

答案 0 :(得分:3)

您必须尝试将输入转换为数字,在这种情况下浮动将是明确的。

请注意,您应该使用raw_input而不是输入。

try:
    chosen = raw_input("Input a number: ")
    number = float(chosen) / float(chosen)
except Exception as e:
    print 'Error: ' + str(e)

答案 1 :(得分:0)

您尝试划分字符串,使用int()转换为int。

try:
    chosen = int(input("Input a number"))
except ValueError:
    print('Not number.')

作为旁注,checking primality的算法存在缺陷,您需要检查数字范围内的每个数字,而不是n的余数除以输入< /强>

a = int(input("Input a number: "))  # Example -> 7
def is_prime(n):
    for i in range(2, n):   
        if n % i == 0: 
            return False
    return True

print is_prime(a)
>>> True

# One-liner version.
def is_prime(n):
    return all(n % i for i in range(2, n))

print is_prime(a)
>>> True

答案 2 :(得分:0)

问题是input()返回一个字符串而不是一个数字。 您首先需要将chosen转换为chosen = float(chosen)的数字。那么数学运算应该可以正常工作..

答案 3 :(得分:-1)

input()函数返回string而不是int。尝试转换它或使用raw_input()代替:

方法1:

chosen = int(input("Input a number"))
number = (chosen) / chosen

方法2:

chosen = raw_input("Input a number")
number = (chosen) / chosen