Python程序在IDLE中工作,但不在命令行中(PowerShell)

问题描述:

我目前正在尝试编写一个函数来询问一个数字,并返回它是否为素数。我打算使用raw_input()函数获取输入。这个程序工作,如果我在Python键入并运行它,但是当我在PowerShell中运行它,我收到以下错误:Python程序在IDLE中工作,但不在命令行中(PowerShell)

>>> python ex19.1.py 
What is your number? 34 
Traceback (most recent call last): 
    File "ex19.1.py", line 13, in <module> 
    is_prime(number) 
    File "ex19.1.py", line 5, in is_prime 
    if n % 2 == 0 and n > 2: 
TypeError: not all arguments converted during string formatting 

我目前正在运行的Python 2.7,而我不知道为什么我会因为我没有在我的代码中使用任何字符串格式化程序,所以接收到字符串错误。以下是我用于我的程序的代码,名为ex19.1.py。

import math 

def is_prime(n): 
    if n % 2 == 0 and n > 2: 
     return False 
    for i in range(3, int(math.sqrt(n)) + 1, 2): 
      if n % i == 0: 
       return False 
    return True 

number = raw_input("What is your number? ") 
is_prime(number) 

我的问题是,为什么这个错误出现了,我能做些什么来解决它?谢谢!

number为你提交使用它的运算操作应该是一个整数。但是,使用raw_input的是字符串

只要将它转换为int

number = int(raw_input("What is your number? ")) 

  • 模运算字符串用于字符串格式化,用格式字符串和格式参数一起。 n % 2尝试使用整数2格式化字符串“34”(格式字符串“34”不需要参数时)。这是此特定错误消息的原因。

当您从raw_input获取输入时,默认情况下它是一个字符串。

事情是这样的:

>>> n = "2" 
>>> n % 2 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: not all arguments converted during string formatting 

为了解决您的问题,投n为int,然后你的代码将正常工作。

这样的:

try: 
    num = int(number) 
    is_prime(num) 
except ValueError as e: 
    #Some typechecking for integer if you do not like try..except 
    print ("Please enter an integer")