所以我正在尝试设计一个模拟花园的程序,这是我编写的函数之一,它是用户输入植物名称的一个函数,例如羊齿植物或苹果树。
def add_plant(plant_list, total_food,):
new_plant = get_valid_name("")
if new_plant in plant_list:
print("invalid choice")
elif len(new_plant) > total_food:
print(f"{new_plant} would cost {len(new_plant)} food. with only {total_food}, you can't afford it")
else:
plant_list.append(new_plant.title)
used_food = len(new_plant)
total_food -= used_food
return total_food我的代码如下,我这样写它的原因是我想确保程序在没有输入任何东西或用户输入数字的情况下循环回来。但我发现,当我试图通过添加红薯或苹果树等植物来测试它时,我得到的结果是无效的选择打印。
我想知道如何编码这个错误检查,以便它检查空格和数字,同时还允许用户输入长度超过一个单词的植物名称。
def get_valid_name(plant,):
while True:
plant = input("Enter plant name:").title()
if plant.isalpha():
return true
else:
print("Invalid plant name")发布于 2021-05-21 02:33:29
使用string.replace()删除空格,并为每个字符测试isdigit()或isalpha()。
Pythons any()函数将在迭代时测试是否满足任何条件,因此测试字符是否既不是数字也不是字母字符。它还短路,所以它比列表理解更快。
def get_valid_name(plant):
is_valid = False
while not is_valid:
plant = input("Enter plant name:").title()
without_spaces = plant.replace(' ', '')
is_valid = not(any(!(c.isdigit() or c.isalpha()) for c in without_spaces))
return plant发布于 2021-05-21 02:49:53
像这样怎么样?
def get_valid_name():
while (plant := input().strip()).isdigit() or not plant: pass
return plant.title()https://stackoverflow.com/questions/67626007
复制相似问题