没有用户输入时如何重复功能

问题描述 投票:1回答:1

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

我尝试使用True或如果不是。我最接近解决问题的方法是程序再次要求输入数字,仅此而已。

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]:

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

python if-statement user-input
1个回答
0
投票

使用循环。

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
© www.soinside.com 2019 - 2024. All rights reserved.