【问题标题】:How can I print more than one variable for an input in python?如何在 python 中为输入打印多个变量?
【发布时间】:2021-12-20 22:41:04
【问题描述】:

我是一个初学者,基本上我想做的是一个程序,它可以读取一个字符串并在检查后显示适当的消息:

a.只包含字母

b.只包含大写字母

c.只包含小写字母

d.仅包含数字

e.仅包含字母和数字

f.以大写字母开头

g.以点结尾

msg = input("Please enter your message: ")

if msg.isalpha() == True:
    aux = "Your message contains only letters."
    print(aux)

elif msg.isupper() == True:
    print("Your message contains only uppercase letters.")

elif msg.islower() == True:
    aux = "Your message contains only lowercase letters."
    print(aux)

elif  msg.isdigit() == True:
    print("Your message contains only digits.")

elif  msg.isalpha() and msg.isdecimal() == True:
    print("Your message contains only letters and numbers.")

elif  msg.capitalize() == True:
    print("Your message begins with a capital letter.")

elif  msg.endswith(".") == True:
    print("Your message ends with a dot.")

这是我的代码,但它只打印我创建的一两个变量。例如,当我输入“ABCD123”时,它会打印出消息只包含大写字母,但我也希望它打印出我的消息包含字母和数字。

【问题讨论】:

  • 您只希望它打印其中一条消息还是所有相关消息?
  • 您还可以删除 if 语句中的 == True,因为这些方法返回 bool 值。

标签: python python-3.x


【解决方案1】:

您的代码只会打印其中一个输出,因为您使用的是“elif”。从您的问题来看,您似乎希望使用单独的 if 语句来避免条件检查一旦满足就会中断。如:

if msg.isalpha() == True: aux = "Your message contains only letters." print(aux)

if msg.isupper() == True: print("Your message contains only uppercase letters.")

if msg.islower() == True: aux = "Your message contains only lowercase letters." print(aux)

【讨论】:

    【解决方案2】:

    你应该使用 if 而不是 elif。在这种情况下,一旦您输入第一个“if”,程序就会停止并且不会检查您使用 elif 设置的其他条件。

    【讨论】: