对于 python 中的循环菜单?



大家好,我对python相当陌生,我对创建菜单有一些问题......

所以我最近使用while循环制作了一个菜单,它的工作方式就像它应该的那样。但是,我的问题是是否可以使用for循环创建菜单。我知道当您希望某些东西循环x次时,会使用for循环。

我已经尝试寻找答案,但我真的找不到任何相关的东西。如果有人能指出我正确的方向,我将不胜感激。

这是我使用"while"的菜单:

def mainMenu():
print("SELECT A FUNCTION")
print("")
print("e1- Calculate The Area Of A Sphere")
print("e2- Calculate The Volume Of A Cube")
print("e3- Multiplication Table")
print("e4- Converting Negatives To Positives")
print("e5- Average Student Grades")
print("e6- Car Sticker Color")
print("e7- Exit")
print("")
while True:
selection = input("Enter a choice: ")
if(selection == "e1"):
e1()
break
elif(selection == "e2"):
e2()
break
elif(selection == "e3"):
e3()
break
elif(selection == "e4"):
e4()
break
elif(selection == "e5"):
e5()
break
elif(selection == "e6"):
e6()
break
elif(selection == "e7"):
print("Goodbye")
break
else:
print("Invalid choice. Enter 'e1'-'e7'")
print("")
mainMenu()

我的猜测是你的教练希望你使用发电机。根据您的问题,我将假设您不熟悉发电机。如果您已经了解它们,请跳到第二部分,否则可能值得您花时间先了解它们。

发电机

简而言之,生成器的作用类似于函数,但不使用 return 语句,而是使用 yield 语句。在生成器上调用 next 将运行它,直到它到达 yield 语句,然后暂停进程(并保存生成器的状态,而不是正常函数,它通常不会在调用之间保存状态),直到再次在生成器上调用下一个,此时控制流将从生成器停止的地方恢复。

以下代码应该让您了解生成器的工作原理:

# Define a generator function. This function will return our generator iterator.
def test_gen():
numCalls = 0
print("Start. This code is only executed once.")
while numCalls < 10:
print("Entering while loop.")
yield("Yielding. numCalls = %d." %(numCalls))
numCalls += 1
print("Resuming control flow inside generator.")
print("End. This code is only executed once.")
yield("Last yield.")
# End test_gen.
# Test the behavior of our generator function.
def run_test_gen():
# Create generator iterator by calling the generator function.
gen = test_gen()
# Continuously get the next value from the gen generator.
while True:
# If the generator has not been exhausted (run out of values to yield), then print the next value.
try:
print(next(gen))
# Break out of the loop when the generator has been exhausted.
except StopIteration:
print("Generator has been exhausted.")
break
# End run_test_gen.
run_test_gen()

如果你想了解更多关于生成器的信息,我会看看Python文档和Jeff Knupp的解释。

使用生成器和 for 循环制作菜单

现在我们知道了生成器,我们可以使用它们来创建基于 for 循环的菜单。通过在生成器中放置一个 while True 语句,我们可以创建一个产生无限数量值的生成器。由于生成器是可迭代的,我们可以在 for 循环中迭代生成的值。有关示例,请参阅下面的代码。

def infinite_gen():
"""
First, create a generator function whose corresponding generator iterator 
will yield values ad infinitum. The actual yielded values are irrelevant, so 
we use the default of None.
"""
while True:
yield
# End infinite_gen.
def print_str_fun(string):
"""
This function simply returns another function that will print out the value
of string when called. This is only here to make it easier to create some
mock functions with the same names that you used.
"""
return(lambda : print("Calling function %s." %(string)))
# End print_str.
# Create a tuple of the function names that you used.
fun_name_tuple = ('e%d' %(ii) for ii in range(1, 7))
# Create a dictionary mapping the function names as strings to the functions themselves.
fun_dict = {fun_name: print_str_fun(fun_name) for fun_name in fun_name_tuple}
# Add the e7 function separately because it has distinct behavior.
fun_dict['e7'] = lambda : print("Goodbye.")
def mainMenu():
"""
Example mainMenu function that uses for loop iterating over a generator
instead of a while loop.
"""
# Create our infinite generator.
gen = infinite_gen()
# Iterate over the values yielded by the generator. The code in the for loop
# will be executed once for every value yielded by the generator.
for _ in gen:
# Get function name from user input.
selection = input("Enter a choice: ")
# Try to call the function selected by the user.
try:
fun_dict[selection]()
break
# Print a note to user and then restart mainMenu if they supplied an
# unsupported function name.
except KeyError:
print("Invalid choice. Enter 'e1' - 'e7'.")
print()
mainMenu()
# End mainMenu.
# Allows one to run the script from the command line.
if __name__ == '__main__':
mainMenu()

最新更新