自從我編寫代碼以來,它已經有一段時間了,所以我試圖再次回到它,但是我遇到了一些代碼問題。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。
愚蠢的問題:哪一個**是**第17行?逐字添加完整的錯誤! (順便提一下,這是很明顯的事情) –
你有一個函數外的'return'語句。在check_valid(uinput):'block時,你希望'return True'做什麼? 'return'只在函數*中具有含義*,而'while'循環不在函數中。 –
謝謝你所有的迴應!所有這些都非常有幫助。另外,第17行的@MarcusMüller是'if(usrnameinput!= usrnameinput.isalpha())或(len(usrnameinput)> = 12):' – Bearclaw