函数间变量传递问题:Python交通流量计算代码调试求助
Fixing Traffic Flow Calculation: Variable Passing & Logic Issues
Let's walk through fixing your code step by step—you're running into two main problems: incorrect variable passing between functions, and broken conditional logic in the number_of_busy_days function.
First, Fix the traffic_intensity Function
Your original code has a small oversight: converting count to an integer doesn't do anything unless you assign the result back to the variable. Here's the corrected version:
def traffic_intensity(count): """Number of cars passing by""" # Convert count to integer and assign it back to the variable count = int(count) if count < 5000: level = "Very Low" elif 5000 <= count < 10000: level = "Low" elif 10000 <= count < 18000: level = "Moderate" elif count >= 18000: level = "High" return level
Next, Fix the number_of_busy_days Function
This is where the variable passing and logic issues are most noticeable:
- You tried to pass
leveltotraffic_intensity, butlevelis a variable only defined insidetraffic_intensity—it doesn't exist in the scope ofnumber_of_busy_days. Instead, you need to pass the currentcountfrom your loop. - Your conditional check
if traffic_intensity(level) == "Moderate" or "High"is invalid Python syntax for what you want. Theor "High"part will always evaluate toTrue(non-empty strings are truthy), so every day would be counted as busy. - You didn't finish incrementing the
daily_countsvariable.
Here's the corrected function:
def number_of_busy_days(counts): """Busy days based on traffic flow""" daily_counts = 0 for count in counts: # Get the traffic level for the current day's count current_level = traffic_intensity(count) # Check if the level is Moderate OR High if current_level == "Moderate" or current_level == "High": daily_counts += 1 # Return the total number of busy days return daily_counts
How to Test It
You can test this with a sample list of daily counts to make sure it works:
# Sample daily traffic counts daily_traffic = [4500, 8000, 12000, 20000, 17000] print(number_of_busy_days(daily_traffic)) # Should output 3 (days with 12000, 20000, 17000)
Key Takeaways
- Variable Scope: Variables defined inside a function are only accessible within that function. To use a function's output, you need to call the function with the correct input parameters and store its return value.
- Conditional Logic: When checking multiple values with
or, you need to repeat the full comparison each time (or useinto check membership in a list, likeif current_level in ["Moderate", "High"]). - Type Conversion: Always assign the result of type conversion back to the variable—otherwise, the conversion has no effect.
内容的提问来源于stack exchange,提问作者Excelize
相关产品推荐
相关产品推荐

