为什么我的函数陷入无限循环?

huangapple go评论85阅读模式
英文:

Why is my function running into infinite loop?

问题

I have recently began learning Python, appreciate your response on this.

I have written the definition of get_int() and get_float() differently on purpose because I wanted to understand what happens if I accept the input in main() and pass that value during function call. Here is my code:

#!/usr/bin/env python3

def get_int(prompt, low, high):
    while True:
        #number = float(input(prompt))
        if prompt <= low or prompt > high:
            print("Entry should be greater than ", low, "and less than or equal to ", high)
        else:
            return prompt

def get_float(prompt, low, high):
    while True:
        number = float(input(prompt))
        if number <= low or number > high:
            print("Entry should be greater than ", low, "and less than or equal to ", high)
        else:
            return number    

def calculate_future_value(monthly_investment, yearly_interest, years):
    # convert yearly values to monthly values
    monthly_interest_rate = yearly_interest / 12 / 100
    months = years * 12

    # calculate future value
    future_value = 0.0
    for i in range(months):
        future_value += monthly_investment
        monthly_interest = future_value * monthly_interest_rate
        future_value += monthly_interest

    return future_value

def main():
    years = 0
    monthly_investment = 0.0
    yearly_interest_rate = 0.0
    choice = "y"
    while choice.lower() == "y":
        # get input from the user
        monthly_investment = get_float("Enter monthly investment: ", 0, 1000)
        yearly_interest_rate = get_float("Enter yearly interest rate: ", 0, 15)
        years = int(input("Enter number of years: "))
        years = get_int(years, 0, 15)

        # get and display future value
        future_value = calculate_future_value(
            monthly_investment, yearly_interest_rate, years)

        print(f"Future value:\t\t\t{round(future_value, 2)}")
        print()

        # see if the user wants to continue
        choice = input("Continue? (y/n): ")
        print()

    print("Bye!")

if __name__ == "__main__":
    main()

I am having problem only with the get_int(). As you see, I have passed low=0 and high=15. If I input years as 0 or 16, then it displays infinite print statement specified in the "if" clause but there is no problem when I input value within the range.

I'm not entirely sure if I can use the function argument directly in the function definition without assigning to a local variable.

If it is indeed allowed, is there a mistake with my "while" loop inside get_int()? or do I include a while loop in the main() itself where I'm accepting the int value?

Thanks in advance!

1: link to a screenshot

英文:

I have recently began learning Python, appreciate your response on this.

I have written the definition of get_int() and get_float() differently on purpose because I wanted to understand what happens if I accept the input in main() and pass that value during function call. Here is my code:

#!/usr/bin/env python3
def get_int(prompt, low, high):
while True:
#number = float(input(prompt))
if prompt <= low or prompt > high:
print("Entry should be greater than ", low, "and less than or equal to ", high)
else:
return prompt
def get_float(prompt, low, high):
while True:
number = float(input(prompt))
if number <= low or number > high:
print("Entry should be greater than ", low, "and less than or equal to ", high)
else:
return number    
def calculate_future_value(monthly_investment, yearly_interest, years):
# convert yearly values to monthly values
monthly_interest_rate = yearly_interest / 12 / 100
months = years * 12
# calculate future value
future_value = 0.0
for i in range(months):
future_value += monthly_investment
monthly_interest = future_value * monthly_interest_rate
future_value += monthly_interest
return future_value
def main():
years = 0
monthly_investment = 0.0
yearly_interest_rate = 0.0
choice = "y"
while choice.lower() == "y":
# get input from the user
monthly_investment = get_float("Enter monthly investment: ", 0, 1000)
yearly_interest_rate = get_float("Enter yearly interest rate: ", 0, 15)
years = int(input("Enter number of years: "))
years = get_int(years, 0, 15)
# get and display future value
future_value = calculate_future_value(
monthly_investment, yearly_interest_rate, years)
print(f"Future value:\t\t\t{round(future_value, 2)}")
print()
# see if the user wants to continue
choice = input("Continue? (y/n): ")
print()
print("Bye!")
if __name__ == "__main__":
main()

I am having problem only with the get_int(). As you see, I have passed low=0 and high=15. If I input years as 0 or 16, then it displays infinite print statement specified in the "if" clause but there is no problem when I input value within the range (see screenshot: https://drive.google.com/drive/u/0/folders/1w4-IhBveZQv0pSDygc1HexNFBDUDNE-B).

I'm not entirely sure if I can use the function argument directly in the function definition without assigning to a local variable.

If it is indeed allowed, is there a mistake with my "while" loop inside get_int()? or do I include a while loop in the main() itself where I'm accepting the int value?

Thanks in advance!

答案1

得分: 1

while True:get_int 中确实是一个无限循环,该 while 可以通过执行 return(在 else 情况下执行)或 break 语句来中断。由于您的 if 中没有执行类似的语句,循环会继续。

从您的问题看,似乎您根本不想要一个循环,因此,您可以将 get_int 声明为:

def get_int(prompt, low, high):
    #number = float(input(prompt))
    if prompt <= low or prompt > high:
        print("输入应大于", low, "且小于等于", high)
    else:
        return prompt
英文:

while True: within the get_int is indeed an infinite loop, that while can i.e. be broken by executing a return (which you do on the else case) or a break statement. Since you don't execute any similar statement in your if, the loop continues.

As it seems by your question, you don't want a loop at all, therefore, you could just declare the get_int as:

def get_int(prompt, low, high):
#number = float(input(prompt))
if prompt &lt;= low or prompt &gt; high:
print(&quot;Entry should be greater than &quot;, low, &quot;and less than or equal to &quot;, high)
else:
return prompt

答案2

得分: 0

如果 prompt 不正确,不要更新它的值。如果不更新它的值,条件不会改变。如果条件不改变,你只会打印文本而不会返回。

如果 prompt 错误,请刷新它的值

如果用户输入不正确,你仍然需要在某处刷新值。如果你不想在循环开始时提问,可以在提示错误时提问。

def get_int(prompt, low, high):
    while True:
        if prompt &lt;= low or prompt &gt; high:
            print(&quot;输入应大于 &quot;, low, &quot;且小于等于 &quot;, high)
            prompt = int(input(&quot;输入新的值&quot;))  # 你需要询问一个新值
        else:
            return prompt

替代方案:

你可以直接将条件放入 while 循环中:

def get_int(prompt, low, high):
    while prompt &lt;= low or prompt &gt; high:
        print(&quot;输入应大于 &quot;, low, &quot;且小于等于 &quot;, high)
        prompt = int(input(&quot;输入新的值&quot;))
    return prompt

这样做,如果提示正确,你会立即退出循环。如果不正确,你会打印消息并刷新值。

英文:

If prompt is not correct, you don't update its value. If you don't update its value, the condition won't change. If it doesn't change, you will only print the text and never return.

Refresh prompt value if it's wrong

You still need to refresh the value somewhere if the user input is wrong. If you don't want to ask at the beginning of the loop, ask when the prompt is wrong.

def get_int(prompt, low, high):
    while True:
        if prompt &lt;= low or prompt &gt; high:
            print(&quot;Entry should be greater than &quot;, low, &quot;and less than or equal to &quot;, high)
            prompt = int(input(&quot;Enter a new value&quot;))  # You need to ask a new value
        else:
            return prompt

Alternative:

You can put the if condition directly in the while loop:

def get_int(prompt, low, high):
    while prompt &lt;= low or prompt &gt; high:
        print(&quot;Entry should be greater than &quot;, low, &quot;and less than or equal to &quot;, high)
        prompt = int(input(&quot;Enter a new value&quot;))
    return prompt

Doing so, you quit the loop right away if the prompt is correct. If it is not, you print the message and refresh the value.

huangapple
  • 本文由 发表于 2023年3月7日 19:39:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75661503.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定