gpt4 book ai didi

python - 如何在输入无效之前调用函数?

转载 作者:行者123 更新时间:2023-11-28 17:20:10 24 4
gpt4 key购买 nike

我是 python 的新手,我想知道如何在用户提供无效输入之前调用函数。这是一个代码示例:

start = input("For sum of squares, type 'squares'. For sum of cubes, type 'cubes'. "
"\nIf you would like to raise a number to something other than 'squares' or 'cubes', type 'power'. "
"\nIf you would like to exit, type 'exit':")

def main_function(start):
while start.lower() != "exit":
if start.lower() in "squares":
initial = input("What is the initial constant for the sum of the squares: ")
terms = input("Number of terms: ")

if start.lower() in "cubes":
initial = input("What is the initial constant for the the sum of the cubes: ")
terms = input("Number of terms: ")



if start.lower() in "power":
initial = input("What is the initial constant for the the sum: ")
terms = input("Number of terms: ")

else:
print("Program halted normally.")
quit()

main_function(start)

我想让它做的是在用户输入正确输入时重新提示“开始”,然后让它再次运行该函数。我曾尝试将“start”放在“else”语句上方和下方的函数中,但它从不接受新输入。

最佳答案

我会这样做,在方法中定义开始输入并在循环内调用它,当它等于 "exit" 时而不是中断循环。

也可以使用 elif,这样如果第一个条件语句为 True 则您将不会检查其他条件语句,当然除非这是您想要的。

def get_start_input():
return input("For sum of squares, type 'squares'. For sum of cubes, type 'cubes'. "
"\nIf you would like to raise a number to something other than 'squares' or 'cubes', type 'power'. "
"\nIf you would like to exit, type 'exit':")

def main_function():
while True:
start = get_start_input()
if start.lower() == "squares":
initial = input("What is the initial constant for the sum of the squares: ")
terms = input("Number of terms: ")

elif start.lower() == "cubes":
initial = input("What is the initial constant for the the sum of the cubes: ")
terms = input("Number of terms: ")

elif start.lower() == "power":
initial = input("What is the initial constant for the the sum: ")
terms = input("Number of terms: ")

elif start.lower() == "exit":
print("Program halted normally.")
break

main_function()

编辑:

正如 dawg 在评论中所写,最好在此处使用 == 而不是 in 因为您可以有多个匹配项和含糊不清的含义。

关于python - 如何在输入无效之前调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42014723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com