You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3新手求助:loop()运行后无法接收新输入并应用到函数

Fixing Your Tax Tool's Loop & Input Handling Issues

Hey there! Congrats on building your first app after 3 weeks of learning— that's awesome! Let's figure out why your loop isn't updating with new inputs and get it working right.

The Core Problems in Your Code

Let's break down the main issues first:

  • Variable Scope: Your amount and rate variables are defined globally, but when you redefine them inside loop(), they're local to that function. Functions like tot_with_tax() still use the original global values instead of the new ones you enter.
  • Misplaced Function Calls & Returns: The line return in_page(), tot_with_tax_exit(), print(tot_with_tax()), loop() in loop() calls all these functions at once, creating messy execution flow. Recursively returning loop() also isn't the cleanest way to handle repetition here.
  • Unreliable Exit Check: tot_with_tax_exit() relies on the global amount, so it won't see the new values you enter in the loop, and the int(0) check is unnecessary (just compare to 0 directly).

Fixed Version of Your Code

Here's a revised version that addresses all these issues:

from os import sys

def say_bye():
    print("GoodBye!")
    sys.exit()

def loop():
    while True:
        print("\nWould you like to enter another value?")
        choice2 = input('y/n: ')
        if choice2.lower() == 'y':
            print()
            amount = float(input("enter another price: "))
            # Check exit condition right after entering amount
            if amount == 0:
                print('\nWould you like to exit?')
                choice = input('y/n?: ')
                if choice.lower() == 'y':
                    say_bye()
                else:
                    # Skip to next iteration to let user re-enter
                    continue
            rate = float(input("tax rate: "))
            calculate_and_print_total(amount, rate)
        else:
            say_bye()

def calculate_and_print_total(amount, rate):
    tax = amount * rate
    total = tax + amount
    print(f"\nYour total after tax is: {total}")

def welcome_page():
    print("\nWelcome to the tax tool!")
    print("\nPlease enter your total price, and tax rate.")

# Initial setup
welcome_page()
initial_amount = float(input("enter price: "))
if initial_amount == 0:
    print('\nWould you like to exit?')
    initial_choice = input('y/n?: ')
    if initial_choice.lower() == 'y':
        say_bye()
initial_rate = float(input("tax rate: "))
calculate_and_print_total(initial_amount, initial_rate)

# Start the loop
loop()

Key Changes Explained

  • No More Global Variables: We pass amount and rate as parameters to calculate_and_print_total() so every new input is used directly, eliminating confusion between global and local values.
  • Cleaner Loop Logic: Replaced the recursive loop() call with a while True loop, which is easier to follow and avoids potential stack overflow issues with deep recursion.
  • Simplified Exit Check: Moved the "exit if amount is 0" logic directly into the input flow, so it checks the new value immediately instead of relying on a separate function that can't access local variables.
  • Renamed Functions for Clarity: in_page() → welcome_page() and combined tot_with_tax()/tot_with_tax_exit() into calculate_and_print_total() to make the code more readable.
  • Case Insensitivity: Added .lower() to input checks so users can enter 'Y' or 'N' too, making the tool more user-friendly.

Give this a try— it should now accept new inputs in the loop and calculate the correct total every time!

内容的提问来源于stack exchange,提问作者AFK Aaron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 20:42:43