[英]Python program works in IDLE, but not in command line (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)
我的問題是,為什么會出現此錯誤,我該如何解決? 謝謝!
您使用number
進行算術操作時, number
應該為整數 。 但是,使用raw_input
獲得的是string 。
只需將其轉換為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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.