我有一个问题,用户可以输入空格或什么都不输入,但仍然可以通过程序,我如何防止这种情况发生?我还是python的初学者。
def orderFunction(): # The function which allows the customer to choose delivery or pickup
global deliveryPickup
deliveryPickup = input("Please input delivery or pickup: d for delivery p for pickup")
if deliveryPickup == "d":
global customerName
while True:
try:
customerName = (input("Please input your name"))
if customerName == (""):
print("Please input a valid name")
else:
break
global customerAddress
while True:
try:
customerAddress = (input("Please input your name"))
if customerAddress == (""):
print("Please input a valid Address")
else:
break
global customerPhnum
while True:
try:
customerPhnum = int(input("Please input your phone number"))
except ValueError:
print("Please input a valid phone number")
else:
break
print("There will also be a $3 delivery surcharge")
elif deliveryPickup == "p":
customerName = (input("Please input your name"))
if customerName == (""):
print("Please input a valid name")
orderFunction()
else:
print("Please ensure that you have chosen d for Delivery or p for Pickup")
orderFunction()
orderFunction()
这是我的尝试,但我得到了各种各样的无凹痕和缩进错误,我认为我的while循环可能是错误的。
本质上,如果我在其中一个客户输入(例如customerName)中输入一个空格或按enter键,它就会被存储起来。这需要防止,我已经尝试过使用while循环来修复它,但显然没有起作用。
希望有人能解决这个问题
非常感谢。
.strip()
删除字符串前后的所有制表符或空格。 表示所有空格==空字符串。所有制表符==空字符串。所以你要检查一下绳子的长度!=0或字符串不为空。只需使用无限循环来继续强制输入正确的内容。在作为一个提示,你不必把自己局限于一个功能。 下面是一个工作代码。在
如果你需要更多的checks来增加你的循环。在
首先,不需要在前两个循环上使用try语句。不要使用try语句,除非您预期出现错误,您需要使用except语句来处理,就像在bottomwhile循环中那样。在
然后你只需要给你的前两个循环添加更多的条件,我不知道你到底想阻止什么,但是你可以尝试检查输入的长度,也可以看看下面的答案,找到一个有趣的方法: https://stackoverflow.com/a/2405300/8201979
尝试使用一个regular expression来检查是否插入了“a-Z”之间的任何字符,如果没有,则给出一个错误
相关问题 更多 >
编程相关推荐