如何修正Python代码:将自定义函数inputs中的输入变量传递至主程序并实现重复输入功能
Got it, let's work through fixing your code step by step. You're hitting two key issues here: local variable scope (your main program can't access variables created inside the inputs() function) and missing logic to repeat the input process for multiple bidders. Here's how to fix both:
1. Fix Variable Access: Return Data from the Function
Variables defined inside a function are local to that function—meaning the code outside can't see them. To pass those values back to the main program, we need to have the inputs() function return the collected data. A tuple works perfectly for this:
def inputs(): key = input("What is your name?: ") value = int(input("What's your bid? ")) # Convert bid to integer for easier comparison later choice = input("Are there any other bidders? Type 'yes' or 'no'. ").lower() return key, value, choice # Send the three values back to the main code
2. Add Logic for Repeating Inputs
To let users add multiple bidders, we'll use a while loop that runs as long as the user says there are more people to bid. We'll also store all bidder data in a dictionary so we can keep track of everyone's info:
print("Welcome to the secret auction program.") bidders = {} # Empty dictionary to store all bidder names and their bids continue_bidding = True while continue_bidding: name, bid, choice = inputs() # Unpack the values returned from the function bidders[name] = bid # Save the bidder to our dictionary # Check if we should keep the auction going if choice == 'no': continue_bidding = False elif choice != 'yes': print("Oops, please type 'yes' or 'no' to continue.") # Optional: Find and announce the highest bidder highest_bid = 0 winner = "" for bidder, amount in bidders.items(): if amount > highest_bid: highest_bid = amount winner = bidder print(f"\nThe winner is {winner} with a bid of ${highest_bid}!")
What Changed?
- Return Values: The
inputs()function now sends back the name, bid, and user choice, so the main program can actually access and use those values. - Loop for Repeats: The
whileloop keeps callinginputs()until the user types 'no', letting you add as many bidders as needed. - Data Storage: We use a dictionary to save all bidders, which makes it easy to calculate the winner later (a nice bonus feature!).
- Bid Conversion: We converted the bid to an integer so we can compare amounts numerically (swap
intforfloatif you need to handle decimal bids).
This version will work exactly as you want—you can repeat the input process, access all the collected data outside the function, and even announce the winner at the end!
内容的提问来源于stack exchange,提问作者B mb

