如何在python中制作长“ IF语句”?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在python中制作长“ IF语句”?相关的知识,希望对你有一定的参考价值。

因此,我试图在要求您进行注册或登录的地方写一个长if语句,但是当我进入登录部分时,会出现语法错误。有任何提示吗?

    registration = input("Do you have a registration")
if registration == "No":
 name = input("Type your name: ")
 surname = input("Type your surname: ")
 userp1 = name[0]+ surname.capitalize()
 print(userp1)
 password = input("Enter your password
")
 userInput = input("Type your login details
")
if userInput == userp1:
     userInput = input("Password?
")
     if userInput== password:                 
       print("Welocome")
change = input("Do you want to change your username?")
if change == "No":
   print("You logged in as" , userp1)
else:
 userp1 = input("What would your new username be?")
 print("You logged in as",userp1)
else:
    print("Login")
答案

您在最后几行中连续写两个else语句,这是无效的语法。您可以将if语句放在另一个if语句中,而必须这样做。这是有效的代码,但我不确定这是否是您要制作的代码:

registration = input("Do you have a registration")
if registration == "No":
    name = input("Type your name: ")
    surname = input("Type your surname: ")
    userp1 = name[0]+ surname.capitalize()
    print(userp1)
    password = input("Enter your password
")
    userInput = input("Type your login details
")
    if userInput == userp1:
         userInput = input("Password?
")
         if userInput== password:                 
           print("Welocome")
    change = input("Do you want to change your username?")
    if change == "No":
       print("You logged in as" , userp1)
    else:
       userp1 = input("What would your new username be?")
       print("You logged in as",userp1)
else:
    print("Login")

另一答案

您的代码缩进得不好。请注意,python对于缩进是有意义的。您也没有指定您得到的错误是什么。因此,我冒昧地尝试了编写与您的代码最大匹配的代码。这里是:

registration = input("Do you have a registration")
if registration == "No":
   name = input("Type your name: ")
   surname = input("Type your surname: ")
   userp1 = name[0]+ surname.capitalize()
   print(userp1)
   password = input("Enter your password
")
   userInput = input("Type your login details
")
   if userInput == userp1:
       userInput = input("Password?
")
       if userInput== password:                 
         print("Welocome")
   change = input("Do you want to change your username?")
   if change == "No":
      print("You logged in as" , userp1)
   else:
      userp1 = input("What would your new username be?")
      print("You logged in as",userp1)
else:
    print("Login")

以上是关于如何在python中制作长“ IF语句”?的主要内容,如果未能解决你的问题,请参考以下文章

如何在没有错误的情况下制作if-else语句?

试图弄清楚如何将具有多个条件的长三元运算符转换为长if语句

python 用于在终端中运行的sublime text 3的简单代码片段制作工具

如何正确格式化 Coffeescript 中的长复合 if 语句

python中循环语句

如何在python中为一个if语句设置多个条件[重复]