python - 没有用户输入时如何重复该功能
问题描述
我的程序应该存储联系人。当我输入号码时,如果没有用户输入,我需要程序继续询问号码。现在,即使用户输入没有输入数字,我的程序也会考虑添加的联系人。
我尝试使用一段时间 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]:
正如我所说,如果没有用户输入,程序应该继续询问一个数字,并且只有在有用户输入时才进入下一步。
解决方案
使用循环。
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
推荐阅读
- google-admin-sdk - 如何在没有oauth2的g套件中创建新用户
- r - ggsave 和 gganimate 的“动画”中符号的大小一致
- javascript - Symfony 4 - 使用带有 webpack encore 的 Algolia 地方
- nuget - Artifactory 中的 Nuget 异常
- python - 如何检查字符串列表中的字符串是否在熊猫数据框列中
- java - 按顺序对数组进行排序
- javascript - javascript中的函数语法
- postgresql - 定义子实体与使用类型列之间的性能差异
- angular - Angular 8:mat-datepicker 的问题。我尝试使用 [startAt] 禁止选择今天之前的日期
- c# - 如何安装 Emgu.cv xamarin 表单