【发布时间】:2016-10-12 13:35:26
【问题描述】:
我已经有一段时间没有编写代码了,所以我试图重新开始编写代码,但是我的一些代码遇到了问题。
我想编写一个简单的程序,它接受用户的输入并检查它是否全是没有空格的字母,并且长度小于 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
对不起,我是个菜鸟。今天也刚加入 Stack Overflow。
【问题讨论】:
-
愚蠢的问题:哪一个是第17行?逐字添加完整的错误! (顺便说一句,这是显而易见的事情)
-
您在函数之外有一个
return语句。你希望return True在while check_valid(uinput):块中做什么?return仅在 在函数中 有意义,而您的while循环不在函数中。 -
感谢您的所有回复!所有这些都非常有帮助。另外,@MarcusMüller,第 17 行是
if (usrnameinput != usrnameinput.isalpha()) or (len(usrnameinput) >= 12): -
@Bearclaw 不要把它放在评论中,把它放在实际问题中。并添加完整的错误。
-
这里发布的代码没有语法错误,除了我提到的
return的使用。所有check_valid函数都可以正常解析。
标签: python if-statement syntax-error