2016-06-11 119 views
-4

自從我編寫代碼以來,它已經有一段時間了,所以我試圖再次回到它,但是我遇到了一些代碼問題。Python - 在if語句中找不到語法錯誤

我想編寫一個簡單的程序,它接受用戶的輸入並檢查它是否全部是沒有空格的字母,並且長度小於12.我一直收到第17行的「無效語法」錯誤我運行代碼,在if語句之後指向冒號,該語句檢查用戶名是否只是字母,少於12個字符。我知道這意味着在此之前線路上有錯誤,但是在哪裏?

#import the os module 

import os 

#Declare Message 

print "Welcome to Userspace - Your One-Stop Destination to Greatness!" + "\n" + "Please enter your username below." \ 
+ "\n" + "\n" + "Username must be at least 12 characters long, with no spaces or symbols." + "\n" + "\n" 

#uinput stands for user's input 

uinput = raw_input("Enter a Username: ") 

#check_valid checks to see if arguement meets requirements 

def check_valid(usrnameinput): 
    if (usrnameinput != usrnameinput.isalpha()) or (len(usrnameinput) >= 12): 
     os.system('cls') 
     print "Invalid Username" 
     return False 
    else: 
     os.system('cls') 
     print "Welcome, %s!" % (usrnameinput) 
     return True 

#Asks for username and checks if its valid 

print uinput 
check_valid(uinput) 

#Checks input to check_valid is correct, and if it is not, then ask for new username input and checks it again 

while check_valid(uinput): 
    return True 
    break 
else: 
    print uinput 
    check_valid(uinput) 

print "We hope you enjoy your stay here at Userspace!" 

更新 - 我的代碼多一點點打過來,我唯一改變的事情就是while有條件的if

print uinput 
check_valid(uinput) 

#Checks input to check_valid is correct, and if it is not, then ask for new username input and checks it again 

if check_valid(uinput): 
    print uinput 
    check_valid(uinput) 

print "We hope you enjoy your stay here at Userspace!" 

我跑這個代碼,但得到這個錯誤相反:

File "Refresher In Python.py", line 39 
    return True 
SyntaxError: 'return' outside function 

對不起,這樣一個noob。今天剛剛加入Stack Overflow。

+2

愚蠢的問題:哪一個**是**第17行?逐字添加完整的錯誤! (順便提一下,這是很明顯的事情) –

+0

你有一個函數外的'return'語句。在check_valid(uinput):'block時,你希望'return True'做什麼? 'return'只在函數*中具有含義*,而'while'循環不在函數中。 –

+0

謝謝你所有的迴應!所有這些都非常有幫助。另外,第17行的@MarcusMüller是'if(usrnameinput!= usrnameinput.isalpha())或(len(usrnameinput)> = 12):' – Bearclaw

回答

0

我相信這是你想要的。我建議把它分成兩個函數,你的check_valid()和一個普通的main()函數。

def check_valid(usrnameinput): 

    if (not usrnameinput.isalpha()) or (len(usrnameinput) >= 12): 
     print("Invalid name") 
     return False 
    else: 
     print("Welcome!") 
     return True 

def main(): 

    uinput = raw_input("Enter a Username: ") 
    while not check_valid(uinput): #Repeatedly asks user for name. 
     uinput = raw_input("Enter a Username: ") 

main() 
+0

當我嘗試使用你的建議運行它時出現此錯誤:'File'Refresher In Python.py「,第39行 return True SyntaxError:'return'external function'這是一個空行。 – Bearclaw

+0

我相信你有一些干擾這個的其他代碼。如果你運行的是我發佈的內容,那應該不會發生。我剛剛發佈的代碼中沒有「返回」外部函數。 –

+0

我認爲我的IDE有問題,直到我重新啓動程序纔會正確運行代碼。它的工作,謝謝。 – Bearclaw