请不要判断我。.我使用Python才一个月了。 当我躺在床上时,我想到了要在几分钟后创建它,但是我做了很多其他的事情,如果语句和代码看起来很凌乱,我会不断添加不需要的东西。 ) 无论如何,这是我的代码。如果您能告诉我如何正确使用“ elif”语句,那将是很棒的。(我仍在学习python) 问题 :我已尝试多次使用elif语句,但始终出现错误。我该如何解决?
key = True # Game key, if this is false the program won't work.
print("Please type a password: ") # Asking for users password
Pass = input()
print("Thank you for typing your password, please make sure it's secure by trying again..") # Ask them to confirm their password by re-typing it
Again = input()
if Pass == Again:
print("Thank you for choosing a working password, please create your character")
print("Please type your username without numbers")
else:
print("Something's wrong with your password or username!")
# Has user confirm if his information is correct
User = input()
print("checking..")
if User.isalpha() and key == True:
print("So your Username is " + User + " and your chosen password is: " + str(Pass))
else:
print("Either your key is broken or something is wrong..")
if len(User) >= 4: # Checking if the chosen username has 4 or more characters in it
print("The length of your Username is: ")
print(str(len(User)))
print("If this information is correct please type 'true' or 'false'")
else:
print("Please type a username longer than 4 characters!")
answer = input() # I kinda fucked up because my coding is dirty and unorganized lol..
if answer == str(True):
print("Thank you, we're setting up your account! :D")
else:
print("Please re-run the program and fix your information!")
答案 0 :(得分:2)
我们无法调试您尚未发布的代码,并且(如预期的那样-您正在此处进行学习,还有很多要考虑的内容)您的程序结构不是很有用。例如,当用户输入不匹配的密码时,您会告诉他们有关密码,但是仍然继续要求他们提供用户名。不用担心,您将很快学习如何解决它。
由于您询问elif
,因此基本上是else if
的语法缩写,可以避免使用多个缩进级别。假设您希望值'1'
或'2'
采取不同的操作,并宣布其他值无效。你可以写
if value == '1':
#take action appropriate to 1
else:
if value == '2':
# take action appropriate to 2
else:
raise ValueError("Allowed inputs are '1' or '2'")
请注意,不同的动作在不同的缩进级别上。您必须考虑的案例越多,则必须引入更多的缩进级别。因此,通常感觉写起来更具可读性
if value == '1':
# Take action appropriate to 1
elif value == '2':
# Take action appropriate to 2
else:
raise ValueError("Allowed inputs are '1' or '2'")
现在所有动作和决定都处于相同的缩进级别。这几乎就是它的全部。如果不使用else
情况,则根本不会采取任何操作,因此通常用于指定默认操作,在这种情况下会引发异常。
PS:如果要确保在继续操作之前用户输入了两个匹配的密码,请查看while
循环,该循环允许您重复执行一组操作直到出现某种情况(在这种情况下为密码)相等)是真的。
答案 1 :(得分:1)
以下是if3 / ifif / elif / else语句的示例:
test = 'mytest'
if test == 'not_my_test':
print('nope')
elif test == 'mytest':
print('yay')
else:
print('something else')
您可以在此处找到更多信息:https://docs.python.org/3/tutorial/controlflow.html
编辑: 通常,您不应该使用大写字母来定义变量(PEP约定:https://www.python.org/dev/peps/pep-0008/?)
答案 2 :(得分:0)
因此使用Elif
if Pass == Again:
print("Thank you for choosing a working password, please create your character")
print("Please type your username without numbers")
elif Pass != Again:
print("Something's wrong with your password or username!")
尽管您遇到的是什么错误,但如果没有它,我们将无法真正为您提供帮助。