我是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',然后让它再次运行该功能。我已经尝试将'start'放在'else'语句上方和下方的函数中,但它从不接受新的输入。
答案 0 :(得分:2)
我会这样做,在方法中定义开始输入并在循环内调用它,当它等于"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
使用,因为你可以有几个匹配和含糊不清的含义。