gpt4 book ai didi

python - 当用户提供某个关键字作为输入时结束函数

转载 作者:行者123 更新时间:2023-12-03 23:19:59 25 4
gpt4 key购买 nike

当用户在输入中键入特定关键字(例如“off”)时,我如何结束函数而无需在每个输入中添加必要的代码?基本上,当用户在下面的任何输入中的任何地方键入“关闭”一词时,我希望该功能完全停止。我已经创建了一个函数(见代码底部)并尝试在我的代码中放置/调用它,但我不确定将它放在哪里或者我是否可以用一个函数来做到这一点?如果没有,我该如何实现?

  def order_coffee():

drink = input("What would you like? (espresso/latte/cappuccino): ")

user_owes = int(0)

if drink == "espresso":
user_owes = round(1.5, 2)
elif drink == "latte":
user_owes = round(2.5, 2)
elif drink == "cappuccino":
user_owes = round(3.0, 2)

print(f"Please insert coins, you owe ${user_owes}.")
quarters = (int(input("How many quarters?: ")) * .25)
dimes = (int(input("How many dimes?: ")) * .1)
nickels = (int(input("How many nickels?: ")) * .05)
pennies = (int(input("How many pennies?: ")) * .01)

user_paid = round(quarters + dimes + nickels + pennies, 2)
print(f"You have inserted ${user_paid}.")
change = round(user_paid - user_owes, 2)

if user_paid >= user_owes:
print(f"Here is ${change} in change.")
print(f"Here is your {drink} ☕. Enjoy!")
order_coffee()
else:
print("Sorry that's not enough money. Money refunded.")
order_coffee()

order_coffee()

def off():
if input == "off":
return

最佳答案

创建您自己的 input 函数并添加所需的行为:

def my_input(*args, **kwargs):
str = input(*args, **kwargs)
if str == "off":
exit()
return str

这将在用户输入“关闭”时从整个应用程序退出,从函数退出只是抛出异常,并在函数调用之外捕获它。例如:

def my_input(*args, **kwargs):
str = input(*args, **kwargs)
if str == "off":
raise ValueError('Time to go')

和:

  def order_coffee():
try:
# your code
except ValueError as err:
# handle it accordingly
return

更清晰的方法是创建、抛出和处理自定义的Exception。看看这个SO Thread了解如何实现这些自定义异常。

关于python - 当用户提供某个关键字作为输入时结束函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65311742/

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