【问题标题】:Loop statement with two variables带有两个变量的循环语句
【发布时间】:2021-03-07 06:12:35
【问题描述】:

我需要做一个程序,它会询问名字,然后是姓氏。代码应该检测输入是否为小写字母,如果不是,它将重复询问名字和姓氏。

这是我所做的,但它不检测输入是否为小写

firstName = input(“Enter your First Name: “)
lastName = input(“Enter your Last Name: “)

fn = (firstName.islower())
ln = (lastName.islower())

while firstName != fn and lastName != lastName != ln:
     print (“Your First and Last name should be typed in lowercase letter”)
     firstName = input(“Enter your First Name: “)
     lastName = input(“Enter your Last Name: “)


print (“yey!”)

【问题讨论】:

  • 参见falsehoods programmers believe about names,项目编号 12 和 13。您不能强制用户专门以大写或小写形式输入姓名。大写可能很重要。
  • 感谢您的编辑,但您发布的代码有明显的语法错误。只需完全复制/粘贴代码; 不要使用文字处理器将引号替换为“印刷师的引号”等。

标签: python python-3.x loops


【解决方案1】:

除了循环条件中的一些愚蠢的逻辑错误之外,您的代码还不错。这是一个更正的版本:

firstName = input("Enter your first name: ")
lastName = input("Enter your last name: ")

while not firstName.islower() or not lastName.islower():
     print("Your first and last name should be typed in lowercase letters")
     firstName = input("Enter your first name: ")
     lastName = input("Enter your last name: ")

print ("yey!")

【讨论】:

    【解决方案2】:

    在这段代码中,我们检查名字和姓氏是否都是小写,如果不是,用户需要重试。 我希望是你想要的。

    first_name = ""
    last_name = ""
    while True:
        # Receive the first name and the last name from the user
        first_name = input("Enter your first name: ")
        last_name = input("Enter your last name: ")
        # check if the first name and the last name are in lower case if yes it exit otherwise print try again
        if first_name.islower() and last_name.islower():
            break
        print("Your first name and last name need to be in lowercase please try again")
    print("yay!")
    

    实际上,在您的第一次尝试中,您真的很接近它。 我已经做出了这些改变:

    • 无需在循环外进行输入。只是复制代码,并在一个地方输入更容易:)。
    • 需要检查循环内的字符串是否为小写。并检查您收到的每一个输入,直到找到一个好的输入。

    【讨论】:

    • input 总是返回一个字符串。条件first_name is not None 始终为真。为什么要检查它?
    猜你喜欢
    • 2016-10-02
    • 2013-08-30
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    相关资源
    最近更新 更多