2013-03-19 89 views
2

此代碼轉換期間,所有參數給出了一個錯誤的Python:不是字符串格式化

print('type a whole number:') 
n = input() 
if n % 2 == 1: 
    print('Odd'); 
else: 
    print('Even'); 

我假設有一個在if語句一些特別的東西我必須做的變量n?我是Python的初學者。

+1

的Python 2.x或Python 3.x都有??? – pradyunsg 2013-03-19 10:11:29

+1

@Schoolboy它肯定是py3.x,因爲input()在py2.x中返回一個整數,並且錯誤'不是所有在字符串格式化過程中轉換的參數'都清楚地表明'input()'在這裏返回一個字符串。 – 2013-03-19 10:17:59

回答

3

您需要n轉換爲整數首先,從py 3.X input()返回一個字符串:

n = int(input()) 
4

這裏是如何解決它:

n = int(input("type a whole number:")) 

由於input()返回字符串,您需要先使用int()將其轉換爲int。

+0

在Python 2.7中>>> >>> type(input(「type a whole number:」)) 鍵入一個整數:23 '>>> type(raw_input(「type a whole number:」)) 鍵入一個整數:23 ' – kvivek 2013-03-19 10:40:47

+1

因爲像@Ashwini所說的,在Py 3.x input()中返回一個字符串。 – 2013-03-19 10:52:07

0

將用戶輸入n轉換爲首位整數。
即簡單地改變:

n = input() 

到:

n = int(input()) 

此外,input()可以接受字符串作爲參數,其被取輸入之前打印。
所以,你可以改變

print('type a whole number:') 
n = int(input()) 

n = int(input('type a whole number:'))