只是爲了好玩:我已經重寫了這個介紹一些更高級的想法(程序結構,使用enumerate()
,一等功能等)。
# assumes Python 3.x
from collections import namedtuple
def get_int(prompt, lo=None, hi=None):
while True:
try:
val = int(input(prompt))
if (lo is None or lo <= val) and (hi is None or val <= hi):
return val
except ValueError: # input string could not be converted to int
pass
def do_menu(options):
print("\nWhich do you want to do?")
for num,option in enumerate(options, 1):
print("{num}: {label}".format(num=num, label=option.label))
prompt = "Please enter the number of your choice (1-{max}): ".format(max=len(options))
choice = get_int(prompt, 1, len(options)) - 1
options[choice].fn() # call the requested function
def kick_goat():
print("\nBAM! The goat didn't like that.")
def kiss_duck():
print("\nOOH! The duck liked that a lot!")
def call_moose():
print("\nYour trombone sounds rusty.")
Option = namedtuple("Option", ["label", "fn"])
options = [
Option("Kick a goat", kick_goat),
Option("Kiss a duck", kiss_duck),
Option("Call a moose", call_moose)
]
def main():
num = get_int("Please enter the number of iterations: ")
for i in range(num):
do_menu(options)
if __name__=="__main__":
main()
太好了,謝謝! – user2913067