Skip to main content
 首页 » 编程设计

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

2025年05月04日23wuhuacong

我目前正在尝试编写一个函数来请求一个数字,并返回它是否为素数。我计划使用 raw_input() 函数获取输入。如果我在 Python 中键入并运行该程序,该程序可以运行,但是当我在 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”不需要参数时)。这就是此特定错误消息的原因。