2017-02-11 121 views
-2

我是初學者最初學者,我在'elif'後得到了分號的語法錯誤消息爲什麼?另外,如果代碼工作,否則?我的elif語句的這種語法有什麼問題?

#a - this program uses function valid(x) to determine if the user's input is a positive, non-zero number while imposing a limit of 3 attempts 

def valid(x): 
    return (x > 0) 
n = int(input('Please input a positive non-zero number: ')) 
if(valid(n)== True): 
    print(n,'is valid') 
elif: 
    print(u = int(input('error please input a positive non-zero number: '))) 
    if(valid(u)== True): 
     print(u,'is valid') 
elif: 
    print(m = int(input('error please input a positive non-zero number: '))) 
    if(valid(m)== True): 
      print(m,'is valid') 
+0

'elif'也需要一個條件;你在想'別的'。 – Evert

+3

呃...'elif'*什麼*,正是?! – jonrsharpe

+1

@Evert但是不能有兩個'else's,要麼。 – jonrsharpe

回答

0

以下是Python中的if..else條件的語法正確。你跟着這個嗎?

if expression1: 
    statement(s) 
elif expression2: 
    statement(s) 
elif expression3: 
    statement(s) 
else: 
    statement(s) 

ELIF語句可以檢查多個表達式爲TRUE並作爲其中的一個條件值爲TRUE立即執行的代碼塊。在你的代碼片段中,沒有表達式在elif聲明中執行!

我相信你需要像下面這樣的東西。

# This program uses function valid(x) to determine if the user's input is positive, non-zero number while imposing a limit of 3 attempts 
def valid(x): 
    return (x > 0) 

n = int(input('Please input a positive non-zero number: ')) 
if(valid(n)== True): 
    print(n,'is valid') 
else: 
    n = int(input('error please input a positive non-zero number: ')) 
    if(valid(n)== True): 
     print(n,'is valid') 
    else: 
     n = int(input('error please input a positive non-zero number: ')) 
     if(valid(n)== True): 
      print(n,'is valid') 
0

你的語法是無效的,因爲elif是短期的else if,你不必測試的條件。嘗試使用else:

另外,不要與True比較。讓表情獨立。這是不是C或Java,所以周圍的條件語句沒有括號:

if(valid(n)== True): 
    print(n,'is valid') 

變爲:

if valid(n): 
    print(n, 'is valid') 
+0

你不能多次使用'else:'。 – zondo

+0

我認爲這只是格式不好的問題。那裏有一個縮進的「if」。 –

+0

這可能是;我沒有想到這一點。不過,如果不是,我會建議在答案中說清楚。 – zondo

0

只是提供一個更簡潔的解決方案(和pythonic)。 elif需要一個條件。您可以使用for循環來檢查密碼三次。如果密碼正確,則循環結束。

def valid(x): 
    return x > 0 

for i in range(3): 
    n = input('Please input a positive non-zero number: ') 
    if valid(n): 
     print(n, 'is valid') 
     break