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

时间:2016-12-24 19:56:27

标签: python powershell

我目前正在尝试编写一个要求输入数字的函数,以及返回是否为素数的函数。我计划使用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)

我的问题是,为什么会出现这个错误,我该怎么做才能解决它?谢谢!

2 个答案:

答案 0 :(得分:3)

当你使用它提交算术动作时,

number应该是整数。但是,使用raw_input获得的是字符串

只需将其转换为int

即可
number = int(raw_input("What is your number? "))
  • 字符串的模运算用于字符串格式化,以及格式字符串和格式参数。 n % 2尝试格式化字符串&#34; 34&#34;使用整数2(当格式字符串不需要参数时#34; 34&#34;)。这是造成此特定错误消息的原因。

答案 1 :(得分:2)

当您从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")
相关问题