我需要创建 4 个四个变量(
first_name
、generic_location
、whole_number
和plural_noun
),然后让代码自动制作一个短篇故事。我很新,所以请耐心等待。
我想要
制定一些安全措施,要求对除“whole_number”之外的所有变量的响应都是英语词典中的实际单词。
将所有 True 输入路由到 if 语句,该语句将控制是否输出故事故事。
这是我到目前为止所想到的:
first_name = input("Enter a first name.");
if first_name.isalpha():
first_name = True;
print(first_name);
else:
first_name = False;
print("Please use only letters.");
whole_number = input("Enter a whole number.");
if whole_number.isdigit():
whole_number = True;
print(whole_number);
else:
whole_number = False;
print("Please use only numbers.");
plural_noun = input("Enter a plural noun.");
if plural_noun.isalpha():
plural_noun = True;
print(plural_noun);
else:
plural_noun = False;
print("Please use only letters.");
generic_location = input("Enter a generic location.");
if generic_location.isalpha():
generic_location = True;
print(generic_location);
else:
generic_location = False;
print("Please use only letters.");
print(end='');
if(first_name, whole_number, plural_noun, generic_location == True):
print(first_name, "buys", whole_number, "different types of", plural_noun, "at", generic_location, ".");
else:
print("Oops please double check your answers!");
我的期望:
我希望我错了,但我希望不是。
我认为我通过将所有变量标记为“True”,将变量正确路由到作为短篇故事父级的 if 语句。
但是我不知道我是否应该将“short_story”也设置为变量,还是多余的,因为命令只打印一次代码?
if(first_name, whole_number, plural_noun, generic_location == True):
print(first_name, "buys", whole_number, "different types of", plural_noun, "at", generic_location, ".");
else:
print("Oops please double check your answers!");
您不必等到所有输入结束才查看变量是否正确,而是可以不断询问相同的问题,直到用户得到正确的答案。这样,除非所有变量都是正确的格式,否则您将永远无法获得最终打印结果。
while not (first_name := input("Enter a first name: ")).isalpha():
print("Please use only letters.")
while not (quantity := input("Enter a quantity: ")).isdigit():
print("Please use only numbers.")
while not (plural_noun := input("Enter a plural noun: ")).isalpha():
print("Please use only letters.")
while not (location := input("Enter a location: ")).isalpha():
print("Please use only letters.")
# format with an fstring
print(f'{first_name} buys {quantity} different types of {plural_noun} at {location}.')