如果有多个if条件的while语句怎么办?

时间:2019-12-24 09:37:13

标签: python python-3.x

从此处开始学习python,并希望通过我的在线课程进行一些修改:

while True:
    print("What is your name?")
    name = input()
    character = int(len(name))
    if character < 3 or character > 20:
        print("Name can only less than 3 character and no more than 50 character")
    else:
        print(f"Welcome back, {name}")
        break

基本上我希望我的代码能做到:

  1. 输入名称
  2. 如果名称少于3个字符,则会显示错误消息,并返回输入名称
  3. 如果名称超过50个字符,则会显示错误消息,并且会再次输入该名称
  4. 如果名称大于3且小于50,则会显示欢迎消息。

我的代码完全按照其说的去做,但是我想知道是否可以通过每个条件定制通知。任何帮助将不胜感激,因为这是我可以通过stackoverflow浏览的内容。 (或我能理解的最简单的方法)

3 个答案:

答案 0 :(得分:1)

添加,否则添加:像这样的语句

while True:
    print("What is your name?")
    name = input()
    character = int(len(name))
    if character < 3:
        print("Name can only less than 3 character and no more than 50 character")
    elif character > 50:
        print("Error message")
    else:
        print(f"Welcome back, {name}")
        break

答案 1 :(得分:0)

尝试添加elif

实例:

elif character > 50:
    print("name is {} characters long, please try again".format(character))

答案 2 :(得分:0)

您可以在if内添加实际数字的支票。

if character < 3 or character > 50:
    print("Name can only have more than 3 character" if character < 3 else "Name can only have less than 50 character")

或者仅在两种情况下都使用常规消息

if character < 3 or character > 50:
    print(f"Name must be between 3 and 50 characters, {character} where inserted")

您还可以撤消检查以删除else

if 2 < character < 51:
    print(f"Welcome back, {name}")
    break
print(f"Name must be between 3 and 50 characters, {character} where inserted")