从此处开始学习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
基本上我希望我的代码能做到:
我的代码完全按照其说的去做,但是我想知道是否可以通过每个条件定制通知。任何帮助将不胜感激,因为这是我可以通过stackoverflow浏览的内容。 (或我能理解的最简单的方法)
答案 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")