2016-12-24 115 views
1

我目前正在嘗試編寫一個函數來詢問一個數字,並返回它是否爲素數。我打算使用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) 

我的問題是,爲什麼這個錯誤出現了,我能做些什麼來解決它?謝謝!

回答

3

number爲你提交使用它的運算操作應該是一個整數。但是,使用raw_input的是字符串

只要將它轉換爲int

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

  • 模運算字符串用於字符串格式化,用格式字符串和格式參數一起。 n % 2嘗試使用整數2格式化字符串「34」(格式字符串「34」不需要參數時)。這是此特定錯誤消息的原因。
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") 
相關問題