定义一个函数或循环,如果给定的整数参数小于 X 或拒绝接受小于 3 的值,则重新启动
Define a function or loop, which restarts if given integer-parameter is less than X, or refuses to accept value less than 3
我正在编写一个简单的程序,一个人可以去旅行,但旅行必须持续 3
天 最少。整个程序有更多的部分都运行良好,整个程序运行良好,但现在我想增强它并将函数 hotel_cost(days)
的最小参数值设置为 3
在最基本的形式中,我的功能是:
def hotel_cost(days):
# hotel costs 140$ per day
return 140 * int(days)
上面显然有效,但我想更改它,使其不接受小于 3。
我正在尝试使用 while 和布尔值,但它给了我 None
,而且我还遇到了意外的无限递归。抱歉,如果这个问题太基础了,这是我的第一个问题。我尝试搜索但无济于事。
根据我对问题的理解,你可以这样做:
def hotel_cost(days):
if int(days) >= 3:
return 140 * int(days)
else:
return False
然后你可以做:
while not hotel_cost(days):
print("How many days are you staying?")
days = input()
一旦结束,天数和费用将有效。
编辑:
我在 while 循环中编写了代码,以便更清楚地说明我的建议。
希望对您有所帮助。
干杯。
您可以在一个函数中压缩询问用户天数,并在其中给出价格。
def ask_num_hotel_days():
i = int(input("Enter nuber of days: "))
while(i < 3):
print(str(i) + " is not a valid number of days")
i = int(input("Enter nuber of days: "))
return 140 * i
我正在编写一个简单的程序,一个人可以去旅行,但旅行必须持续 3
天 最少。整个程序有更多的部分都运行良好,整个程序运行良好,但现在我想增强它并将函数 hotel_cost(days)
的最小参数值设置为 3
在最基本的形式中,我的功能是:
def hotel_cost(days):
# hotel costs 140$ per day
return 140 * int(days)
上面显然有效,但我想更改它,使其不接受小于 3。
我正在尝试使用 while 和布尔值,但它给了我 None
,而且我还遇到了意外的无限递归。抱歉,如果这个问题太基础了,这是我的第一个问题。我尝试搜索但无济于事。
根据我对问题的理解,你可以这样做:
def hotel_cost(days):
if int(days) >= 3:
return 140 * int(days)
else:
return False
然后你可以做:
while not hotel_cost(days):
print("How many days are you staying?")
days = input()
一旦结束,天数和费用将有效。
编辑:
我在 while 循环中编写了代码,以便更清楚地说明我的建议。
希望对您有所帮助。 干杯。
您可以在一个函数中压缩询问用户天数,并在其中给出价格。
def ask_num_hotel_days():
i = int(input("Enter nuber of days: "))
while(i < 3):
print(str(i) + " is not a valid number of days")
i = int(input("Enter nuber of days: "))
return 140 * i