Python在if语句中找不到语法错误

2024-10-01 07:30:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经有一段时间没有写代码了,所以我试图重新开始,但是我的一些代码遇到了问题。在

我想写一个简单的程序,接受用户的输入并检查它是否都是没有空格的字母,长度是否小于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

^{pr2}$

我运行了这段代码,但是得到了这个错误:

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

对不起,我是个无赖。今天也刚加入堆栈溢出。在


Tags: to代码forinputreturnifoscheck
1条回答
网友
1楼 · 发布于 2024-10-01 07:30:08

我相信这就是你想要的。我建议将它分成两个函数,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()

相关问题 更多 >