python - 当没有用户输入时如何重复该功能

标签 python if-statement user-input

我的程序应该存储联系人。当我输入号码时,如果没有用户输入,我需要程序继续询问号码。目前,即使用户输入没有输入号码,我的程序也会考虑添加联系人。

我尝试使用一段时间 True 或 if not。我最接近解决问题的是当程序第二次要求输入一个数字时,但仅此而已。

def add_contact(name_to_phone):

    # Name...
    names = input("Enter the name of a new contact:")


    # Number...
    numbers = input("Enter the new contact's phone number:")


    # Store info + confirmation
    name_to_phone[names]= numbers
    print ("New contact correctly added")

    return
Select an option [add, query, list, exit]:add
Enter the name of a new contact:Bob
Enter the new contact's phone number:
New contact correctly added
Select an option [add, query, list, exit]:

正如我所说,如果没有用户输入,程序应该继续询问数字,只有在有用户输入时才进入下一步。

最佳答案

使用循环。

def add_contact(name_to_phone):
    while True:
       name = input("Enter the name of a new contact: ")
       if name:
           break

    while True:
        number = input("Enter the new contact's phone number: ")
        if number:
            break

    name_to_phone[name] = number
    print("New contact correctly added")

除了检查输入是否为空之外,您可能还想对姓名和号码进行更彻底的检查。

在 Python 3.8 或更高版本中,您可以简单地每个循环一点。也许这会成为一个标准的习语;也许不是。

while not (name := input("Enter the name...: ")):
    pass

关于python - 当没有用户输入时如何重复该功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58399673/

相关文章:

python - 如果您是《美丽汤》中的 sibling ,则无法找到全部

python - 用 kivy 语言清洁 Canvas

css - Sass 可以识别大小并应用条件吗?

java - 如何测试 ArrayList<String> 中的某个项目是否位于某个位置

java - 更优雅的 Setter 编码方式

python - 使用 PyCharm 分析 Django

python - 在Jupyter notebook中设置环境变量的不同方式

Python:当 False 时继续执行脚本的 if/elif 函数?

javascript - 从没有谷歌地理定位的地址获取纬度/经度

c - 为什么在使用用户输入获取文件名时出现段错误?