2016-11-23 42 views
1

我只是試圖建立一個功能要求一個正整數,然後驗證輸入確實是一個正整數:簡單的功能要求正整數,驗證輸入

def int_input(x): 
    x = input('Please enter a positive integer:') 
    if x != type(int()) and x < 1: 
     print("This is not a positive integer, try again:") 
    else: 
     print(x) 

int_input(x) 

它給我「NameError :名稱'x'未定義「。

它是如此可笑的簡單,我覺得我應該已經找到很多職位對這個所以也許我瞎了......

謝謝!

+0

您正在使用哪個Python版本? –

+0

目前還不清楚爲什麼你的函數首先將'x'作爲參數,但最後一行肯定會傳遞一個未定義的'x'變量。 –

+0

@MoinuddinQuadri 3.5 – Alex

回答

0

您定義了該函數,然後將其稱爲傳遞x作爲參數,但x確實未在int_input(x)的作用域(本例中爲全局)中定義。

你的代碼的一些更正確的版本是:

def int_input(x): 
    if x != type(int()) and x < 1: 
     print("This is not a positive integer, try again:") 
    else: 
     print(x) 

x = input('Please enter a positive integer:') 
int_input(x) 

此外,這種比較:

x != type(int()) 

永遠是False因爲type(int())將永遠是int(A型),而x是一個值。哦,你也應該傳遞一個值到int(),否則它總是返回0

+0

我只是不明白爲什麼我不能將x = input(...)部分包含到函數中,這樣我只需調用該函數就可以詢問用戶輸入了什麼?至於第二部分,我確實有一種感覺,它會給我的問題 – Alex

+0

你可以,但在這種情況下,你不需要傳遞任何參數到你的函數。所以你應該把它的定義改爲'def int_input():'並且通過'int_input()'而不是'int_input(x)'來調用它' – lucasnadalutti

1
def int_input(): 
    x = input('Please enter a positive integer:') 
    if x != type(int()) and x < 1: 
     print("This is not a positive integer, try again:") 
    else: 
     print(x) 

int_input() 

它應該是這樣的,你cannt調用一個函數int_input()沒有聲明x

0

我相信你的意思是讓代碼拒絕浮點值以及負值?在這種情況下,您需要在if語句中說or而不是and

def int_input(x): 
    if x != type(int()) or x < 1: 
     print("This is not a positive integer, try again:") 
    else: 
     print(x) 

x = input('Please enter a positive integer:') 
int_input(x) 

此外,我不知道你使用的是哪個版本的python。 3.x應該可以正常工作,但如果您使用2.x,則在用戶輸入字符串時會出現故障。爲了防止出現這種情況,您可以添加一個像這樣的除外:

def int_input(x): 
    if x != type(int()) or x < 1: 
     print("This is not a positive integer, try again:") 
    else: 
     print(x) 

try: 
    x = input('Please enter a positive integer:') 
    int_input(x) 
except: 
    print("This is not a positive integer, try again:")